JavaScript Hoisting

How JavaScript Runs Code: Two Phases

JavaScript runs code in two main steps:

  1. Memory Creation Phase:
    The JavaScript engine scans the code and:
  2. Execution Phase:
    The code runs line-by-line, assigning values to variables and running functions.

What is Hoisting?

Hoisting is when JavaScript prepares all variable and function declarations before running the code, so they can be used earlier in their scope. It doesn't actually move the code but sets them up in memory.

For var , the variable is set to undefined until its value is assigned. For let and const , you can't use them before their declaration line (they're in the Temporal Dead Zone ).

Function declarations are fully ready to use anywhere, but function expressions (like var x = function() {} ) aren't usable until assigned.

Example of Function Hoisting

This function works before it's defined because function declarations are fully hoisted.

    
hi(); // Output: Hello
function hi() {
console.log("Hello");
}
    
    

Example of Function that is Not Hoisted (Function Expression)

This function does not work before it's defined because function expressions are not hoisted.


hi(); // Error: Cannot access 'hi' before initialization

const hi = function () {
    console.log("Hello");
};

hi(); // Output: Hello

Temporal Dead Zone (TDZ)

Variables with let or const are set up in memory but can't be used until their declaration line. This waiting period is called the Temporal Dead Zone (TDZ). Trying to use them early causes an error.

            
console.log(x); // ReferenceError: Cannot access 'x' before initialization let x = 10;