Hoisting

JavaScript's default behavior of moving declarations to the top of their scope before code execution, allowing you to use variables and functions before they are declared.

Overview

Hoisting is JavaScript's mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. However, only declarations are hoisted, not initializations. Understanding hoisting helps avoid bugs and write more predictable code.

Example

javascript
// Function hoisting
sayHello(); // Works!

function sayHello() {
  console.log('Hello');
}

// Variable hoisting (var)
console.log(x); // undefined (not an error)
var x = 5;

// let and const are NOT hoisted the same way
console.log(y); // ReferenceError
let y = 10;

Key Points

  • Function declarations are fully hoisted
  • var variables are hoisted but initialized as undefined
  • let and const are in temporal dead zone until declared
  • Only declarations are hoisted, not assignments
  • Best practice: declare variables at top of scope

Learn More