What Is Hoisting? 🚀
Hoisting is JavaScript’s mechanism where declarations of variables (var) and functions are moved to the top of their containing scope during the compile phase—before the code actually runs. However, initializations are not hoisted; only declarations are.
🆚 Variable Hoisting: var vs let/const
〽️ Function Hoisting: Declaration vs Expression
-
In contrast, function expressions (e.g., using var) don’t hoist the assigned function—only the variable:
sayHi(); // TypeError: sayHi is not a function
var sayHi = function () {
console.log("Hi");
};
⏱ Execution Context & Hoisting Phases
Before execution, the JavaScript engine performs two stages:
-
Creation phase: variables and function declarations are registered—vars get undefined, functions are fully available.
-
Execution phase: code runs line by line, assignments happen in place.
Why Hoisting Matters: Real-World Impact
-
Using var inside control structures like if or for doesn’t create block scope—it’s function-scoped, which often leads to surprising behavior.
-
TDZ helps catch bugs that would otherwise slip through silently with var.
🧹 Best Practices for Clean and Bug-Free Code
-
Declare variables at the top of their scope to avoid undefined surprises.
-
Prefer let and const over var—they enforce safer, block-scoped behavior.
-
Define functions before usage, or use function declarations (not expressions) when you intend to call them earlier.
Understanding hoisting—and the subtle differences between declaration types—is key to writing predictable, maintainable JavaScript. Let me know if you’d like code examples, visual diagrams, or comparison tables—I’d be happy to add!