Hoisting is the process where javaScript interpreter moves the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code. Only the declarations are hoisted, not the initialisations. This is not a physical move. It happens in memory.
In this post I will explain how variable and function hoisting works in javaScript.
Variable Hoisting
console.log(x) var x = 10;
In the above code snippet we try to access the variable before it is declared and initialised. Can you guess what would be the outcome of the above code ? Will it throw an error ?
Thanks to hoisting in javaScript, there will be no error and you will see undefined printed in the console. This is how javaScript interpreter sees our code.
var x; console.log(x); x = 10;
The reason why we see undefined is “A variable in JavaScript contains undefined before a value is assigned to that variable “
Why did we use var to declare the variable above ? What about let and const ?
It is incorrect to say that only variables declared with var keyword is hoisted. Variables declared with let and const supports hoisting as well. But only the variables declared with var keyword is initialised and variables declared with let and const remain uninitialised.
Function Hosting
sayHello(); function sayHello() { console.log('Hello'); }
sayHello function has been invoked before it is declared. But function declarations hoisted. Therefore this will print Hello to the console.
Can we hoist an arrow function ?
No, we cannot hoist an arrow function.
sayBye(); const sayBye = () => console.log('Bye');
I have defined sayBye as an arrow function. But I invoke it before I defined it. This code will throw an error : ReferenceError: sayBye is not defined. The reason for this is only function declarations are hoisted. Not the initialisation. Arrow functions are anonymous. So it does not make any sense to have an arrow function without initialising it. Therefore like traditional functions, arrow functions cannot be hoisted.