Explain hoisting in JavaScript.
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Hoisting moves declarations to the top of their scope during compilation: var initializes as undefined, function declarations initialize fully, and let/const stay uninitialized until execution reaches them (TDZ).
Detailed explanation
JavaScript executes two passes. During creation, the engine scans the scope and allocates memory for declarations before running any code. Function declarations are hoisted completely, so you can call them before they appear in source. var declarations are hoisted but initialized to undefined, giving undefined instead of an error on early access. let and const are hoisted too — the binding exists — but remain uninitialized until the engine evaluates the declaration line, producing a ReferenceError if touched earlier: the Temporal Dead Zone. Class declarations behave like let. Function expressions follow the rules of the variable holding them, so a var-assigned arrow function is unusable before its line. Understanding hoisting as 'creation phase vs execution phase' is more accurate than the common myth that code physically moves.
Example
sayHi(); // works — full function declaration hoisted
function sayHi() { console.log('hi'); }
console.log(x); // undefined — var hoisted & initialized
var x = 5;
// console.log(y); // ReferenceError — TDZ
let y = 10;Interview tip
Structure the answer around the creation phase and execution phase. Distinguishing 'declaration registered' from 'initialized' separates senior answers from junior ones.
Common mistakes
- Saying let/const are 'not hoisted' — they are, just without initialization.
- Ignoring that hoisting is per-scope, not just global or top-of-function.