Variable Hoisting
Variable Hoisting
Section titled “Variable Hoisting”Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before code execution.
Visual Explanation
Section titled “Visual Explanation”flowchart TD subgraph Compilation["Compilation Phase (Before Execution)"] A1["var x → memory: undefined"] A2["function greet() → entire function in memory"] A3["let y → memory: TDZ (uninitialized)"] end
subgraph Execution["Execution Phase (Line by Line)"] B1["console.log(x) // undefined"] B2["x = 5 // assignment runs"] B3["console.log(y) // ❌ ReferenceError (TDZ)"] B4["let y = 10 // TDZ ends"] end
Compilation --> ExecutionHoisting Behavior by Declaration Type
Section titled “Hoisting Behavior by Declaration Type”// 1. var — hoisted, initialized as undefinedconsole.log(a); // undefinedvar a = 5;
// 2. let — hoisted, but in TDZ (uninitialized)console.log(b); // ❌ ReferenceErrorlet b = 10;
// 3. const — same as let (hoisted, TDZ)console.log(c); // ❌ ReferenceErrorconst c = 15;
// 4. Function declarations — fully hoistedgreet(); // "Hello!" — entire function is hoistedfunction greet() { console.log("Hello!");}
// 5. Function expressions — only variable hoisted// sayHi(); // ❌ TypeError: sayHi is not a functionvar sayHi = function() { console.log("Hi!");};🎯 Interview Tip
Section titled “🎯 Interview Tip”Q: “Are
letandconsthoisted?” A: “Yes! They are hoisted, but they’re placed in the Temporal Dead Zone. Unlikevar, they are NOT initialized withundefined. This is why accessing them before declaration throws aReferenceErrorinstead of returningundefined.”