JavaScript Hoisting. What happens behind JavaScript ?
mimansha-swarup
Posted on August 26, 2021
If you are looking for hoisting in JavaScript you might come across this definition."Hoisting is JavaScript's default behavior of moving declarations to the top".
But what actually happens behind JavaScript ?
Hoisting reefer to the process where compiler allocate memory for variable and function before executing code.
NOTE:- Declarations that are made using var are initialized with a default value of undefined. Declarations made using let and const are not initialized as part of hoisting.
Lets see how JavaScript work Behind?
When a JavaScript Code is executed Execution Context is created.
What is Execution Context?
Execution Context is an abstract concept that hold information about environment within which code is being executed
When we run JavaScript Code Execution Context is Created in two phase Memory Creation and Code Execution
if we break down Execution Context we have 2 component
- Memory
- Code
Memory Part is also called as Variable Environment.
Code Part is known as Thread of Execution.
Consider a code block
var n=2;
function message(){
console.log("Hello JavaScript");
}
console.log(n);
message();
Output of this code block will be
2
Hello JavaScript
When we will run this code Global Execution Context will be created and memory will be allocated to each variable and function after that only code will be allocated.
when variable n is encountered JavaScript reserve a memory space for n. Then JavaScript will store a special value undefined
and for function it will store entire function.
This is what happens under the hood.
Now consider
console.log(n);
message();
var n=2;
function message(){
console.log("Hello JavaScript");
}
we are logging 'n' and calling function before declaring , we should be getting error but JavaScript works differently like we saw memory is allocated before execution
that's why output will be
undefined
Hello JavaScript
so this is how it works you can access these variable and method even before actually initialization in your code
Posted on August 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 18, 2022