Hoisting in JavaScript

Hoisting in JavaScript

This is a process where the JavaScript interpreter appears to move the declarations to the top of the scope before execution.

Now, what does this mean exactly? let's see with an example:

//let's decalre a function first 
function hello (){
    console.log("Hello World")

Now usually what we do is, declare a function and then we call it after that. We follow this best practice to avoid any bugs right?

But here is a thing we can call it before declaring it.

//Here let's see how , 
// now let's call the function on the top and the the declaration.
function hello (){
    console.log("Hello World")

//output will be : "Hello World"

This is strange right? How can this happen? Well, this the what we call hoisting.
it looks like the function declaration is lifted to the top then the function is called. but it's not what it looks like, let's see what is happening behind the scenes.

Before execution, the code is scanned for variable declarations, and for each variable, a new property is created in the variable environment object.

But wait is it possible in all scenarios? NOPE, let's see where hoisting is applicable.
Function declarations, var variables but let and const variables are not hoisted.

and if you are trying to use function expressions and arrows then hoisting depends if var or let / const is used.

let's see an example in var,

// if i'm logging a variable named x without declaring it.

// output: it will give a errro , saying x is not defined .

// But if i say var x  here,

var x;

//now the output will be : undefined , although we are declaring the variable after using it it's not giving us an error.
//But if we will do the same thing with let or const then it will be not possible.

//but now if we assign some value to x here then what will be the output,

x = 9;

//output will be stil : undefined 
//So we found that declaration is hoisted to the top but initialization is not.

But what will happen if we use let instead of var,

let x = 9;

//output will be : error : can't access x before initialization.
// here we expect let to be hoisted as var but it's not , here it goes in to temporary dead zone

I hope you find it useful, let me know your thoughts on this in the comments. make sure to Follow me and subscribe to my newsletter.

If you have any issues or questions about it, feel free to contact me. Thank you 🌟 for reading! like, share and subscribe to my newsletter for more!

🔗Debasish Lenka

Did you find this article valuable?

Support Debasish Lenka by becoming a sponsor. Any amount is appreciated!