DEV Community

Cover image for Hoisting in JavaScript
Muskan Chhatrasal
Muskan Chhatrasal

Posted on • Updated on

Hoisting in JavaScript

Hoisting is the default behavior of JavaScript where all the variable and function declarations are moved on top. πŸ”Ό

Points ↖️ to Remember :

πŸ‘‰JavaScript compiler moves 🚡 variables and function declaration to the 🀘 topπŸ”Ό and this is called hoisting.

πŸ‘‰Only variable declarations move 🚴 to the 🀘 top, ‴️ not the 🀘 initialization.

πŸ‘‰Functions definition moves 🚡🚢 first πŸŒ“ before variables.

πŸ‘‰This means 😏 that irrespective of where the variables and functions are declared, they πŸ’ are moved on top ⬆️ of the scope.
The 🀘 scope can be both local and global.

Why does JavaScript hoist variables?

when you run your js code :
global execution context(just a wrapper) is created

It is created in 2 phases
1) creation phase
2)Execution phase

In the creation phase javascript engine allocates memory to all variables and function in the code and important thing is entire function(fun body) will sit in that memory block and coming to variables in the creation engine don't know what the variable value is going to be by the end because we can manipulate it later
in the code right ?

So in the creation phase instead of storing actul value it will undefined(a placeholder or a sticker)
ex = myName : undefined

Hoisting in Function checked variable

We should figure out how Hoisting of capacity checked factors happens with the accompanying model:

//function scoped
function myFunc(){
console.log(car);
var vehicle = 'Lamborgini';
}
myFunc(); //undefined

How is hoisting related with scoping in JavaScript?

The scope manages the accessibility of variables. The Scope decides how far the JavaScript will go to look 🧐 for a variable. In the event that it's doesn't exist in the current extension, πŸ€ͺ it'll look πŸ‘€ in the external Scope .

Scope in JavaScript is the area where we have πŸ˜’ Correct βœ… access to a variable / function.

Hopefully, my post has helped you understand the hoisting better!

Top comments (0)