DEV Community

Cover image for Summarizing Namaste πŸ™ JavaScript EP03 (Hoisting)
Abhinav Singh Jamwal
Abhinav Singh Jamwal

Posted on

Summarizing Namaste πŸ™ JavaScript EP03 (Hoisting)

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
image

2->Function declarations are hoisted, while function expressions are not.
image

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.
image

In second one, when the getName() and console.log is moved upwards.
Result is x-> undefined
image

If line 5 is removed from code, reference error is shown in console.
image

console.log(getName) is added.
image

What is happening ???

Lets start with first image.
image

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.

image

image

Now, what about third image ?
image

During memory allocation phase, x is not present in memory. That is the reason why it results in reference error.

Now, what about fourth image?
image

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.

image

In case of arrow functions, it is treated as variable and is assigned a value of undefined instead of function body

image

Latest comments (1)

Collapse
 
jamwal21 profile image
Abhinav Singh Jamwal

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);