Skip to content
javascript questions

JavaScript · 8 of 10junior~1 min

What is hoisting and how does it affect var, let, function declarations?

#core#scope

Hoisting

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase - before any code runs.

Function declarations - fully hoisted

js
sayHello(); // works fine! function sayHello() { console.log('Hello'); }

The entire function is hoisted - you can call it before it's defined.

var - hoisted but not initialized

js
console.log(name); // undefined (not an error) var name = 'Alice'; console.log(name); // 'Alice' // what JavaScript actually sees: var name; // declaration hoisted console.log(name); // undefined name = 'Alice'; // assignment stays

let and const - temporal dead zone (TDZ)

js
console.log(age); // ReferenceError: Cannot access before initialization let age = 25;

let and const are hoisted but not initialized - accessing them before declaration throws an error.

Function expressions - not hoisted

js
sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log('Hi'); }; // var is hoisted as undefined, calling undefined() throws

Summary

HoistedInitializedUsable before declaration
functionYesYesYes
varYesundefinedYes (but undefined)
let / constYesNo (TDZ)No

Hoisting is one of the most common JavaScript interview topics. The key insight is that let and const ARE hoisted - they just aren't usable until the declaration line.

updated

did you know it?

related questions