Best Practices: Declare Before Use
What You'll Learn
You'll understand why writing clear, predictable code means declaring all variables at the top of their scope—avoiding hoisting-related confusion.
The Core Problem with Hoisting
Hoisting is a JavaScript quirk, not a feature you should rely on. While var declarations float to the top and functions get fully hoisted, this behavior creates code that's hard to read and reason about. Someone reading your code shouldn't need to mentally "reorder" it to understand what's happening.
Modern JavaScript (let and const) still hoists declarations, but enforces the Temporal Dead Zone—forcing you to declare before use. This is intentional design to prevent bugs.
The Simple Rule
Declare all variables at the beginning of their scope (top of a function, top of a block). This makes your code:
- Readable: Variables are defined where someone naturally looks first
- Predictable: No surprises about when values exist
- Maintainable: Clear initialization prevents accidental TDZ errors
- Future-proof: Matches how
let/constwork, even if you're usingvar
The Analogy
Think of cooking: you gather all ingredients on the counter before you start. You don't reach into the pantry mid-recipe—that's chaotic and error-prone. Similarly, declare your variables upfront, then use them confidently.
Why This Matters Now
You've learned how hoisting and the TDZ work under the hood. Now forget about exploiting those mechanics. Instead, write code as if hoisting doesn't exist. This single habit prevents entire categories of bugs and makes your code immediately understandable to others (and future-you).
Key Takeaway: Always declare variables before using them—modern JavaScript rewards this practice with fewer bugs and clearer code.