Let's Explore Hoisting in Javascript, in less than Five Minutes
I will explain the concept as I understand it or what comes to my mind when I hear the term hoisting. I will try to make this as simpler as possible.
ok. let's begin.
The term Hoisting is one of the most fascinating terms of js.
The word ‘hoisting’ means lifting something up. In js declarations are hoisted. ex: variables and functions.
Javascript hoists ( lift up ) declarations before the function call. That's why we can call a function before declaring it. If it's an arrow function
which brings me to the next point,
functional-scoped variables and block-scoped variables are hoisted differently.
For example,
var a = 10;
In this single line, js have done three tasks.
var a; //(a ) a = undefined; // ( assign undefined to the variable ) a = 10; ( assign 10 to the variable )
Now, if we write this and run
console.log(a);
var a = 10;
//output : 10
bit weird! because of hoisting, js hoisted those three particular tasks ( declaration, assign undefined, and assign 10 ) before the function call. In this case console.log (a).
js rearranged the code like this,
Recommended by LinkedIn
var a = 10;
console.log(a);
Global scoped variables
console.log(a);
let a = 10;
//output: a is not defined
Interesting…. js should have hoisted the variable before the functional call, then why is it giving the error?
js hoisted the let variable, yes, but differently. As we have discussed before, when we write this,
let a = 10;
three actions happen. declaration, assign undefined, and assign 10.
let a;
a = undefined;
a = 10;
for block-scoped variables, javascript only hoists these two tasks. rather than three of them. like this,
let a;
a = undefined;
what I meant is, js sees the code as
let a;
a = undefined;
console.log(a);
a = 10;
That's why it was giving the error.
So, if I summarize the concept,
Thanks for sharing