Example-With function keyword
Output for the above code is:
undefined and for functions, it will store the whole function definition.
due to this our code gives out as
undefined in case of
x and function definition in case of
Example-With Arrow function
In this example, We will see how hoisting works in the case of arrow functions.
We observed something different in the case of arrow functions 🤔
abc as a variable in the above case and it will assign
undefined in the Memory creation phase.
Will let and const hoisted?
Let's see with an example,
Output for the above code:
So, in the above code, we can't access
y before declaring those. What's this means? are
The answer is YES
const will also be hoisted but in a different way.
As we already know,
const are block-scoped, Will see how these will be hoisted in the browser.
Here, I have put a breakpoint on line number 5, Even before executing line number 5 we can see the variables
y initialized with the special keyword
undefined but in different memory space. This proved that let and const also hoisted.
Now, We will get another question, Why we are not able to access
y if they are hoisted?
let's see another example.
In the above code, we saw that let and const variables are not accessible until and unless they are initialized with some values. The time from variable hoisting to variable initialization Is Temporal Dead Zone (TDZ)
And, during this temporal dead zone time, we cannot access the variables. due to this, we got reference errors in the above examples.
Hoisting is a phenomenon in JS by which we can access variables and functions even before declaring those in our program.
In the case of arrow functions,
undefinedwill be initialized in the memory creation phase.
let and const are also hoisted but in different memory locations.
We cannot access let and const variables before initializing those because of Temporal Dead Zone.
I hope you learnt something new by reading this post. Please like this and share this post with your friends and community, it motivates me to write more awesome blog posts.
Will see you in my next blog post 😊