Hello there!
In this blog we will be discussing what Hoisting and Temporal Dead Zone actually are !
Let us have a look at this code snippet
Example 1 :
var a = 10;
function Greetings(){
console.log('hey!');
}
Greetings(); //hey!
console.log(a); //10
Nothing surprising !! Output is as expected.
But what do you think output for this would be ? will it throw an error?
Example 2:
Greetings(); //Hey
console.log(a); //undefined
var a = 10;
function Greetings(){
console.log('Hey!');
}
YES! And let me say this, This is what Hoisting actually is!
The ability to access variables and functions even before declaring/giving some value to it, without getting an error.
Here we are able to somehow get Hey from the function call, but undefined for a.
And why is that !!
Let us understand a bit more about how javascript actually executes code.
Even before a single line of code is executed, memory is allocated to each variable and function.
NOTE ⚠️ : In case of arrow functions it treats like variables only and assigns undefined.
Have a look at this example.
Example 3:
var a= 20;
function Greetings(){
console.log('Hey!');
}
console.log(Greetings);
// output : f Greetings(){
// console.log('Hey!');
// }
Here, whole function is stored before executing i.e in the memory allocation phase. Whereas in case of variables before initializing a placeholder undefined is allocated for variables.
Example 4 :
console.log(b) // undefined
var b =30;
console.log(b) //30
Are Let and const hoisted as var then ?
Yes! They are hoisted but in another memory space.
They are not part of the global object/window object.
Let's have a look.
Example 5:
var a = 10;
let b =20;
console.log(a) //10
console.log(b) // 20
Nothing New!
But what if we access b before initializing
Now that we have an understanding about hoisting let us get to know what Temporal Dead Zone is! (TDZ)
Example 6:
console.log(a) //undefined
console.log(b) // ReferenceError: Cannot access 'b' before initialization
var a = 10;
let b =20;
same goes for const as well!
Here, b gives a reference error, because b is in TDZ when we are trying to access it.
The time in between the variable is hoisted and assigned some value is called as TEMPORIAL DEAD ZONE.
And we cannot access variables when they are in TDZ.
Here, until b is given 20 ,every line before it is in TDZ. Which is why it throws Reference error.
To avoid Temporal Dead Zone it is recommended to write all initializations on top of your program so that variables doesn't go through TDZ.
However as it is vast topic you might not find it much clear, but hope this helps in better understanding.
see you until next time.
Happy coding :-)