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)