Home Courses Hoisting Explained - var vs let vs const

Hoisting Explained - var vs let vs const

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope during the memory creation phase.

In simple words:

JavaScript processes declarations before executing code.


How JavaScript Executes Code

Execution happens in two phases:

  1. Memory Creation Phase
  2. Variables and functions are stored in memory
  3. Execution Phase
  4. Code runs line by line


Function Hoisting (Fully Hoisted)

Example:


fruit();

function fruit(){
console.log("Fruit function");
}

Output:

Fruit function

Why?

Function declarations are completely hoisted, so you can call them before they are defined.


var Hoisting (Partial Hoisting)

Example:


console.log(fruit);
var fruit = "apple";

Output:

undefined

Explanation:

Only the declaration is hoisted, not the assignment.


var fruit;
console.log(fruit); // undefined
fruit = "apple";

var is initialized with undefined.


let and const Hoisting (Temporal Dead Zone)

Example:


console.log(fruit);
let fruit = "apple";

Output:

ReferenceError: Cannot access 'fruit' before initialization

Explanation:

let and const are hoisted, but they are not initialized.

They remain in the Temporal Dead Zone (TDZ) until execution reaches their declaration.

TDZ is the time between variable creation and initialization.


Function Expression Hoisting

Example:


fruit();

var fruit = function(){
console.log("apple function");
}

Output:

TypeError: fruit is not a function

Explanation:

This is treated like a variable:


var fruit;
fruit(); // undefined()
fruit = function() { ... };

So:

  1. Variable is hoisted
  2. Function is not assigned yet


Function Expression with let


fruit();

let fruit = function(){
console.log("apple function");
}

Output:

ReferenceError

Explanation:

Because let is in the Temporal Dead Zone, it cannot be accessed before initialization.



Share this lesson: