Variables & Scope

var, let, const

The three ways to declare a variable in JavaScript and when to reach for each.

The short version

  • Prefer const by default.
  • Use let only when reassignment is required.
  • Avoid var in new code — it leaks out of blocks.
js
const PI = 3.14159;
let counter = 0;
for (let i = 0; i < 3; i++) counter += i;

Block scope keeps i invisible outside the loop, which is the modern default.

Interview questions

Sign in to save

What is the Temporal Dead Zone?

The period between entering a scope and the `let`/`const` declaration being evaluated. Reading the binding during that window throws a `ReferenceError`.

Is `const` immutable?

The binding is immutable — you cannot reassign it. The underlying value can still be mutated (e.g. pushing to a `const` array).

Practice

Rewrite a `var`-based loop that captures the wrong index in a `setTimeout` so each timeout logs the intended value.

Hint: Switch `var i` to `let i` — each iteration gets its own binding.

Hoisting