HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (to the top of the current script or the current function).


The Concept

In JavaScript, a variable can be used before it has been declared. In many other languages, this would cause an error. JavaScript "hoists" the declaration, but not the initialization.

x = 5; // Assign 5 to x
console.log(x); // Display x
var x; // Declare x

Declaration vs. Initialization

JavaScript only hoists declarations, not initializations. If you declare and initialize a variable at the bottom, the value will be undefined when used at the top.

console.log(y); // Result: undefined
var y = 7; // Initialization is NOT hoisted

Hoisting with let and const

Variables defined with let and const are also hoisted to the top of the block, but not initialized. They are in a "Temporal Dead Zone" from the start of the block until the declaration is processed.

ReferenceError: Using a let or const variable before it is declared will result in a ReferenceError, helping you find potential bugs early!

Function Hoisting

Function declarations are hoisted completely. This means you can call a function before you define it in your code.

hello(); // Works!

function hello() {
  console.log("Hello World!");
}

Note: Function expressions (where a function is assigned to a variable) are not hoisted because they follow variable hoisting rules.


Key Points to Remember

  • Hoisting moves declarations to the top of their scope
  • Only declarations are hoisted, not assignments
  • var hoists as undefined
  • let/const hoist but cause error if used early (Temporal Dead Zone)
  • Functions are fully hoisted (safe to call before declaration)
  • Best practice: Always declare all variables at the top of every scope