JavaScript Hoisting

What Is Hoisting?

In JavaScript, hoisting is the default behavior of moving variable and function declarations to the top of their containing scope (script or function). Only declarations are hoisted—not the assignments.

This means that variables and functions can be used before they are declared, but their values may not be accessible if they are assigned after the usage.

How Hoisting Works

  1. Variable Declarations:
    Variables declared using var are hoisted, but their value remains undefined until the assignment occurs.
    Variables declared with let and const are hoisted but are placed in a temporal dead zone (TDZ) and cannot be accessed until declared.
  2. Function Declarations:
    Function declarations are fully hoisted, meaning you can call the function before declaring it.
  3. Function Expressions and Arrow Functions:
    Function expressions and arrow functions are not hoisted like function declarations. They behave like variables, so they are undefined until the assignment occurs.

Examples of Hoisting

Example 1: Variable Hoisting with var

console.log(a); // Output: undefined
var a = 10;
console.log(a); // Output: 10

Explanation:

  • The declaration var a is hoisted to the top.
  • The assignment a = 10 happens later, so the initial value is undefined.

Example 2: Hoisting with let and const

console.log(b); // Uncaught ReferenceError: Cannot access 'b' before initialization
let b = 20;

console.log(c); // Uncaught ReferenceError: Cannot access 'c' before initialization
const c = 30;

Explanation:

  • Variables declared with let and const are hoisted but remain in the temporal dead zone until their declaration is encountered.

Example 3: Function Declaration Hoisting

greet(); // Output: Hello, world!

function greet() {
console.log("Hello, world!");
}

Explanation:

  • Function declarations are fully hoisted, so you can call the function before its declaration in the code.

Example 4: Function Expression Hoisting

sayHello(); // Uncaught TypeError: sayHello is not a function

var sayHello = function() {
console.log("Hello!");
};

Explanation:

  • The variable sayHello is hoisted but initialized as undefined. Since it’s a function expression, it cannot be called before its assignment.

Differences Between var, let, and const in Hoisting

Featurevarlet and const
Hoisting BehaviorHoisted with undefinedHoisted but in TDZ
Temporal Dead ZoneNot ApplicableApplicable
Re-declarationAllowedNot Allowed

Key Takeaways

  • Hoisting is a JavaScript mechanism that moves declarations to the top of their scope.
  • Only declarations are hoisted; assignments are not.
  • Function declarations are fully hoisted, while function expressions are not.
  • let and const declarations are hoisted but remain inaccessible until declared due to the temporal dead zone.

Leave a Comment