Hoisting in JavaScript ๐Ÿ”ฅ

Hoisting in JavaScript ๐Ÿ”ฅ


2 min read

Everything in JavaScript happens inside an "Execution Context"

Phases of Code Execution:

1. Memory Allocation:

Firstly the variables & functions are placed in the Execution Context - the variables are placed with an "undefined" placeholder and functions are placed as it is with the entire code as shown below:

2. Thread Execution:

In this phase, the actual values of variables are assigned to themselves replacing "undefined" & for the function invocation an entire new Execution Context is created and the memory allocation is stuff is done again for all variables inside the function Then the function executes and returns the value after that the Execution Context is deleted.


Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

console.log(x); //undefined 
console.log(y); //func y(){.....}
console.log(z); //Refrence Error: not defined

let x = 7;
function y(){
    console.log("This is function y!")

Let's break down the Output we got above!

  • variable: x

In the case of x: we are accessing the x variable even before initializing but still, we didn't get any error but got undefined, why?

Because as we saw in the Memory allocation phase the js assigns a special placeholder 'undefined' to all variables.

  • function: y

In the case of function y: In the memory allocation phase the entire function was copied into memory.

so when we console logged the function it didn't give any error but printed the function as it is.

  • variable which doesn't exist: z

As we didn't define the z variable so hoisting didn't occur here, so when we console logged we got Reference Error: not defined.

So this was it for this one! - The declarations of variables & functions were moved to the top of their scope.

You can follow me on other Socials: