What is hoisting in JavaScript?
Quick Answer
Hoisting is the engine processing declarations before executing code. var declarations are hoisted and initialised to undefined. Function declarations are hoisted whole (callable before their line). let/const are hoisted but not initialised — referencing them before the declaration throws (the temporal dead zone).
Hoisting is the engine reading declarations first, before it runs the code. With var, the declaration is moved to the top of the scope and set to undefined, so you can reference it early but it's not the value yet. Function declarations are hoisted completely, so you can call a function above where it's defined. let and const are also hoisted but they're not initialised, so touching them before their line throws — that gap is called the temporal dead zone. If I just declare things before I use them and use const, hoisting basically stops mattering.
console.log(x); var x = 5;→ printsundefined(the declaration moved up, the assignment didn't).greet(); function greet() {}→ works (function declaration fully hoisted).greet(); const greet = () => {}→ReferenceError(const in the TDZ; also it's a function expression, not a declaration).console.log(y); let y = 1;→ReferenceError: Cannot access 'y' before initialization.- Practical advice: declare before use, prefer
const/let, and the whole topic mostly disappears.