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.
Top comments (0)