Episode 1 — Fundamentals / 1.13 — Introduction to JavaScript

1.13.e — Variables: var, let, const & Scope

In one sentence: const and let give you block-scoped bindings with predictable rules — use const by default, let when you must reassign — and reserve var for 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 do maxRetries = 4. Objects can still have mutated innards (const arr = []; arr.push(1) is allowed).
  • let — use when the variable must change (counters, loop indices in for loops with let).

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

Featureconstletvar
Reassign bindingNoYesYes
Redeclare in same scopeNoNoYes (bad)
Block scopeYesYesNo
TDZYesYesNo
Use in new codeDefaultWhen reassignment neededAvoid

6. Key takeaways

  1. const until proven wrong; let when you need reassignment.
  2. Block scope makes if / loop variables local — fewer accidental leaks.
  3. var is for legacy codebases and interviews about hoisting — not for new features.

Explain-It Challenge

Explain without notes:

  1. Why is const user = {}; user.name = "Ada" legal even though user is const?
  2. What is block scope, and how does it differ from var’s scope?
  3. In one sentence: what is the temporal dead zone?

Navigation: ← 1.13.d — Console · 1.13.f — Naming & Clean Code →