What is Hoisting?
You'll learn: How JavaScript behaves as if it "moves" variable and function declarations to the top of their scope before your code runs.
The Core Idea
Hoisting is JavaScript's behavior during the compilation phase where declarations are processed before any code executes. It's as if the JavaScript engine "lifts" all var, let, const, and function declarations to the top of their scope—though the actual code doesn't physically move.
Think of it like reading a book's table of contents before diving into the chapters. JavaScript scans your code first to register what exists, then executes line by line.
How It Works
When JavaScript compiles your code:
- Declarations are registered in their scope (global or function)
- Initializations stay where they are in your code
- Code then executes top-to-bottom
With var, the declaration is hoisted and initialized to undefined:
console.log(message); // undefined (not an error!)
var message = "Hello";
console.log(message); // "Hello"
Behind the scenes, JavaScript treats this as:
var message; // hoisted to top, initialized to undefined
console.log(message); // undefined
message = "Hello"; // assignment stays in place
console.log(message); // "Hello"
With let and const, declarations are hoisted but not initialized—accessing them before their line causes an error (you'll learn why this happens in the next lesson).
Why This Matters
Understanding hoisting explains seemingly odd behaviors and prevents bugs. You now know why you can sometimes reference variables before they appear in your code.
Key Takeaway: Hoisting means JavaScript processes declarations before executing code, but only var gets initialized to undefined automatically—assignments always happen where you write them.