How does JS Hoisting work?
Variable Hoisting is a by the default behaviour of javascript to compile the code in a specific manner. We mostly readout that javascript runs the code line by line. Before starting you should know about two concepts here.
- Variable Declaration
- Variable Initialization
I will not go deep down of declaration and initialization concept, just explaining with a simple example
var z; /* It is a variable declaration */
z=26; /* Its a variable initialization */
We can use both in a single line, like this.
var z=26;
So keep it in your mind that Hoisting is a way where javascript moved the declared variable or functions at the top of its scope. It all happens during the compilation of code.
JS always move declared variable first at the top of the hierarchy or scop.
In the first phase, the javascript engine scans the whole document and hoist the declared variables. Then move to the second phase "execution of that code".
For example
we write a code in this sequence.
var z=10;
console.log(z);
var y=9;
But javascript scan the whole document first and hoist the declared variable at the top of his scop. let see how js compile the code.
var z;
var y;
z=10;
console.log(z);
y=9;
"We can use a variable before its declaration in javascript" But how? let see another example.
w=10; //Initialized variable
console.log (w);
var w; //Declaration of variable
In this case, we never get any error. Because javascript always hoist the declared variable at the top, not initialization on top.
//How JS compile the code
var w;
w=10;
console.log (w);
Another main concept is, JS just hoist all the variables which declared with var, let and const. But a little difference which I want to explain here.
VAR
var c;
console.log(c);
// Output will be"undefined" in this case but
console.log(c);
var c;
// Output will be"undefined" in this case.
LET & CONST
let c;
console.log(c);
// Output will be"undefined" in this case but
console.log(c);
let c;
// Output will be"ReferenceError" in this case but
Let see an example which mostly asked interviewers
var h="Hello";
console.log(h);
function testFunction(){
console.log(h);
var h="world";
}
testFunction();
console.log("World");
What will be the output of this function?
Output: "Hello undefined World"
How JS Hoist this function?
var h;
h="Hello"
function testFunction(){
var h;
console.log(h); //thats the main reason why it return undefined
h="world";
}
testFunction();
console.log("World");
Thanks for your visit.
Regards
Azeem Aleem