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 stayslet 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() throwsSummary
| Hoisted | Initialized | Usable before declaration | |
|---|---|---|---|
function | Yes | Yes | Yes |
var | Yes | undefined | Yes (but undefined) |
let / const | Yes | No (TDZ) | No |
Hoisting is one of the most common JavaScript interview topics. The key insight is that
letandconstARE hoisted - they just aren't usable until the declaration line.
updated
did you know it?