Hoisting
Hoisting
Section titled βHoistingβWhat it means
Section titled βWhat it meansβHoisting is JavaScriptβs behavior of processing variable and function declarations before running any code, so theyβre conceptually βmoved to the topβ of their scope. How this plays out differs by declaration type: function declarations are hoisted fully (usable before their line); var declarations are hoisted but initialized to undefined; let/const are hoisted but stay in a βtemporal dead zoneβ β inaccessible until their declaration line runs.
Examples
Section titled βExamplesβconsole.log(greet()); // works! function declarations are fully hoistedfunction greet() { return "Hello!";}
console.log(x); // undefined -- hoisted, but not yet assignedvar x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initializationlet y = 5;
// Function expressions are NOT hoisted the same wayconsole.log(sayHi()); // TypeError: sayHi is not a functionvar sayHi = function () { return "Hi!";};Common mistake
Section titled βCommon mistakeβRelying on var hoisting and assuming a variable is βsafeβ to use early just because it doesnβt throw β it silently returns undefined instead, which can mask bugs that let/const would catch immediately via a clear error.
function processUser() { console.log(name); // undefined -- no error, but clearly wrong var name = "Alice"; console.log(name); // "Alice"}
// Using let surfaces the bug immediately and loudlyfunction processUser() { console.log(name); // ReferenceError -- forces you to fix the ordering let name = "Alice";}Quick practice
Section titled βQuick practiceβ-
Why can you call a
functiondeclaration before the line itβs defined on, but not a function stored in aconst?Answer
Function declarations are fully hoisted, including their body;const/letvariables (even ones holding a function) are hoisted but remain inaccessible until their declaration line executes. -
What value does a
varvariable have if you read it before its declaration line?Answer
undefinedβ the declaration is hoisted, but the assignment stays in place. -
What is the βtemporal dead zoneβ?
Answer
The period between entering a scope and reaching alet/constdeclaration, during which accessing that variable throws aReferenceErrorinstead of returningundefined.