Hoisting: Why Variables & Functions Move to the Top
Quick Overview
Hoisting moves no code anywhere. Memory is reserved during the first phase, so a `function` declaration is fully available early while a `var` merely exists holding `undefined` until its assignment runs.
Deep Dive
1. What is Hoisting?
Hoisting is JavaScript's default engine behavior of allocating memory space for variable and function declarations during Phase 1 (Memory Creation) before running Phase 2 (Code Execution).
2. Why It Matters
Because memory is created before execution starts, function declarations can be safely invoked before their line of appearance in the source code!
3. Hoisting Behavior: Functions vs. Variables
- Function Declarations: Stored in memory with their full function body during Phase 1. You can call them anywhere in their scope.
varVariables: Initialized withundefinedduring Phase 1. Accessing avarvariable before its assignment line returnsundefined(not a crash!).letandconst: Memory is allocated during Phase 1, but they remain uninitialized in the Temporal Dead Zone (TDZ). Accessing them before initialization throws aReferenceError!
// Function hoisting (Works!)
sayHello(); // Output: "Hello World!"
function sayHello() {
console.log("Hello World!");
}
// Var hoisting (Returns undefined)
console.log(userAge); // Output: undefined
var userAge = 25;
// Let hoisting (Throws ReferenceError!)
// console.log(userName); // ReferenceError: Cannot access 'userName' before initialization
let userName = "Alex";
4. Function Expressions vs. Declarations
Function expressions assigned to variables (var greet = function() {}) hoist as variables, NOT as functions! Calling greet() before assignment throws TypeError: greet is not a function.
// Uncaught TypeError: greet is not a function
// (because 'greet' is currently 'undefined' during execution line 1!)
greet();
var greet = function() {
console.log("Hi!");
};
5. Common Mistakes
- Calling Arrow Functions Before Declaration: Arrow functions assigned to
constorletreside in the TDZ and cannot be called before their declaration line. - Relying on
varHoisting: Relying onvarhoisting creates confusing code where variables are read before assignment. Declare variables at the top of their block.
6. Try It Yourself
Write it yourself. The tests below run against your code.
Fix Variable Assignment Ordering
Examples
7. Next Steps
Use modern arrow functions or declare functions clearly before invocation. Next, let's explore concise ES6 Arrow Functions!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.