Episode 1 — Fundamentals / 1.13 — Introduction to JavaScript
1.13.e — Variables: var, let, const & Scope
In one sentence:
constandletgive you block-scoped bindings with predictable rules — useconstby default,letwhen you must reassign — and reservevarfor reading legacy code.
Navigation: ← 1.13.d — Console · 1.13.f — Naming & Clean Code →
1. Declaring variables
const maxRetries = 3; // binding cannot be reassigned
let score = 0; // binding can be reassigned
score = score + 10;
const— the binding is constant: you cannot domaxRetries = 4. Objects can still have mutated innards (const arr = []; arr.push(1)is allowed).let— use when the variable must change (counters, loop indices inforloops withlet).
2. Block scope (let / const)
A block is code inside { ... } (functions, if, loops, bare blocks).
if (true) {
const secret = 42;
}
// console.log(secret); // ReferenceError — not visible outside the block
Temporal Dead Zone (TDZ): From the start of the block until the let/const line runs, you cannot read the variable — accessing it throws ReferenceError. This catches “use before declare” bugs.
3. var — function scope (legacy)
function demo() {
if (true) {
var x = 1;
}
console.log(x); // 1 — var is NOT block-scoped
}
var is function-scoped (or global if top-level), hoisted (declaration lifted), and allows redeclaration in the same scope — all sources of confusion in large codebases.
Modern rule: Prefer const, then let. Avoid var in new code.
4. Global variables
Top-level var x = 1 in a browser script can create a property on window. let / const at top level do not become window properties (they are global lexical bindings) — another reason to prefer let/const.
5. Comparison table
| Feature | const | let | var |
|---|---|---|---|
| Reassign binding | No | Yes | Yes |
| Redeclare in same scope | No | No | Yes (bad) |
| Block scope | Yes | Yes | No |
| TDZ | Yes | Yes | No |
| Use in new code | Default | When reassignment needed | Avoid |
6. Key takeaways
constuntil proven wrong;letwhen you need reassignment.- Block scope makes
if/ loop variables local — fewer accidental leaks. varis for legacy codebases and interviews about hoisting — not for new features.
Explain-It Challenge
Explain without notes:
- Why is
const user = {}; user.name = "Ada"legal even thoughuserisconst? - What is block scope, and how does it differ from
var’s scope? - In one sentence: what is the temporal dead zone?
Navigation: ← 1.13.d — Console · 1.13.f — Naming & Clean Code →