Hoisting in javascript
Beginners who started javascript, he/she is confounded about the weird behavior of javascript, so we will jump over some of the topics. so to make your understanding simple I wrote this blog.
Lets first understand undefined vs not defined
undefined is a data type in javascript that is basically you have just declared the variable not initialized it. even though we haven't given it any value, it takes some space or some memory. Whereas not defined which we have not even declared the variable and it is not in memory.
see below code snippet for a better understanding.
// ex-1
var x;
console.log(x);
// undefined
console.log(y)
// y is not defined (reference error)
Now let's understand hoisting. Hoisting is a phenomenon in javascript where you can call the variables (var) and function before they get initialized.
Let's see some examples.
//ex-2
something();
function something(){
console.log('something called')
}
// something is called
something2();
function something2(){
console.log(a);
var a =5;
}
// undefined
In the above code, you called something and something2, it will not give an error, only in this case where using the function keyword
//ex-3
console.log(a);
var a = 2;
// undefined
Here we are getting undefined. Because the variable which is declared using var keyword is in the global memory. Where a variable that uses let and const keywords stored in something called script.
//ex-4
console.log(b); // TDZ starts
let b = 4; // TDZ ends
// b is not defined (gives reference error)
//ex-5
{
console.log(c); // TDZ starts
const c = 5; // TDZ ends
}
// c is not defined (gives reference error)
so in the above examples, it does not give an error in the case of the variables that are assigned using the var keyword.
Then what's the issue with let and const? Let and const are hoisted, which means we cannot access them before initialization, because of TDZ ie temporal dead zone.
Both var and let are stored in different memory scopes.
The time when entering in the scope ( {...}) and till the variables get initialized, is called TDZ, as you see in the above examples.
I hope you understand hoisting if you have any doubt, do comment below, I will be happy to answer. Keep coding ๐งโ๐ป