D DevBrainBox

JavaScript Hoisting

JS

What is Hoisting?

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

This means:

  • Variable declarations (var)
  • Function declarations

are "hoisted" (raised) to the top of their scope.

  • But only the declarations are hoisted, not the initializations.

Example with var

console.log(x); // undefined
var x = 5;
console.log(x); // 5

Behind the scenes, JavaScript interprets this like:

var x;
console.log(x); // undefined
x = 5;
console.log(x); // 5

So the var x declaration is hoisted, but = 5 is not. That’s why it prints undefined first.

let and const are NOT hoisted in the same way

let and const are hoisted to the top of their block, but they are not initialized.

They stay in a "temporal dead zone" (TDZ) from the start of the block until the declaration line.

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

Same for const.

Function Hoisting

Function declarations are hoisted with their bodies.

greet(); // Hello!

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

JavaScript moves the whole function definition to the top.

Function expressions are NOT hoisted

If you assign a function to a variable, only the variable is hoisted (not the function body).

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

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

JavaScript does this under the hood:

var sayHello;
sayHello(); // still undefined, not a function yet
sayHello = function() {
  console.log("Hi!");
};

Quick summary table

TypeHoisted?
var✅ Declaration hoisted, initialized as undefined
let / const✅ Declaration hoisted, but in TDZ (not usable)
Function declaration✅ Fully hoisted (definition + body)
Function expression❌ Only variable is hoisted (not initialized)
  • Hoisting moves declarations to the top of their scope.
  • var → hoisted & initialized as undefined.
  • let & const → hoisted but not initialized (TDZ).
  • Function declarations are hoisted completely.
  • Function expressions are not hoisted (only the variable name is).

On this page