Thank you Akshay Saini for this beautiful series. Just summarizing your lessons for whenever I need a quick recap. Same for others. Hope it helps.
What is Hoisting ?
It is JS interpreterβs default behaviour of moving all declarations to the top of the current scope before code execution.
Hoisiting rules
1->Variable declarations are hoisted, while variable definitions are not.
Variables with var are hoisted, initialized, and assigned value of undefined
2->Function declarations are hoisted, while function expressions are not.
The above piece I read last year but still it was not that much clear until I watched Akshay's execution context video :)
Now, lets summarize the hoisting video which I completed yesterday.
Hoisting is a phenomenon in which we can access variable and functions even before they are initialised or assigned some value.
The first image is executing as usual.
In second one, when the getName() and console.log is moved upwards.
Result is x-> undefined
If line 5 is removed from code, reference error is shown in console.
console.log(getName) is added.
What is happening ???
Since we know that even before Js starts executing code, it assigns or memory is allocated to each and every variables and functions
See below 2 images.
During memory allocation phase, x is not present in memory. That is the reason why it results in reference error.
When Js starts executing code, getName is already been initialised with its function code and x is initialised with undefined during memory allocation phase.
That is the reason when line 3 is executed, it results undefined and when line 5 is executed, it shows function body.
In case of arrow functions, it is treated as variable and is assigned a value of undefined instead of function body
Top comments (1)
In case you guys are thinking variable declaration moves first or function declaration??
See this:
alert(abc);
var abc=10;
function abc(){console.log("Function declaration gets hoisted first");}
alert("Variable declaration gets hoisted after F.declaration");
alert(abc);