DEV Community

mimansha-swarup
mimansha-swarup

Posted on

JavaScript Hoisting. What happens behind JavaScript ?

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

Execution Context
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();
Enter fullscreen mode Exit fullscreen mode

Output of this code block will be

2
Hello JavaScript
Enter fullscreen mode Exit fullscreen mode

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.

Memory allocation

This is what happens under the hood.
Now consider

console.log(n);
message();
var n=2;
function message(){
console.log("Hello JavaScript");
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

so this is how it works you can access these variable and method even before actually initialization in your code

Top comments (0)