No, arrow functions are not hoisted. Only function declarations are hoisted in javascript.
greet(); function greet(){ console.log(‘Hello World!‘); } // Hello World!
Function declaration is hoisted.
greet2(); const greet2 = () => console.log(‘Hello World’); // ReferenceError: Cannot access ‘greet2’ before initialization
Arrow function does not get hoisted.
Why arrow functions are not hoisted?
Arrow functions are anonymous function expression. It’s function definition and returned value is assigned to a variable. While variables get hoisted, assignment of value to variable only happens when we we actually execute the code.
Let me illustrate it with var and const.
console.log(greet2); // undefined greet2(); var greet2 = () => console.log(‘Hello World’); // TypeError: greet2 is not a function
When we run code, javascript engine will save variables and function definition in memory. At this stage variable declared with var is initialized with undefined value. This is hoisting. Any assignment to variable whether it is string, number, boolean, object or function definition does not happen yet. It will first parse through the code and store variables and function definition for future use and then execute code line by line from top to bottom order. At this stage assignment of value to variable occurs.
So in our example above, first var greet2 is initialized with undefined value and saved in memory. After that javascript starts executing the code. Our first line of code is console.log(greet2) which gives us undefined. After that we invoked greet2 before assigning arrow function definition to it. This resulted in TypeError because value of greet2 is still undefined and you cannot invoke undefined. You can only invoke function.(Functions are the only callable object in javascript)
greet2(); const greet2 = () => console.log(‘Hello World’); // ReferenceError: Cannot access ‘greet2’ before initialization
Similarly const and let also get hoisted but unlike var they are not initialized with undefined value. They are uninitialized and remain initialized until value is assigned to it.
Here in our code example, our first line of code is greet2(). We are invoking const greet2 before assigning arrow function definition to it. Basically, we are invoking initialize value therefore we got ReferenceError.
You will get the same error if you console log const greet2 before the assignment.
console.log(greet2); // ReferenceError: Cannot access ‘greet2’ before initialization const greet2 = () => console.log(‘Hello World’);
Variable declare with let will also give same errors as const if it is called before arrow function is defined.