The short answer

#

Use const for everything by default, switch to let only when you need to reassign the variable, and do not use var in new code. const and let are block scoped and fail loudly when misused, while var is function scoped and has quirks that cause real bugs.


_10
const apiUrl = "https://api.example.com"; // never reassigned
_10
let retries = 0; // reassigned below
_10
_10
while (retries < 3) {
_10
retries += 1;
_10
}

Why it happens

#

var is the original way to declare variables. let and const arrived in ES2015 to fix its problems. There are three differences that matter.

Scope

var is scoped to the nearest function. let and const are scoped to the nearest block, which is any pair of curly braces: an if, a loop, or a bare block.


_10
if (true) {
_10
var a = 1;
_10
let b = 2;
_10
}
_10
_10
console.log(a); // 1, because var leaks out of the block
_10
console.log(b); // ReferenceError: b is not defined

Hoisting and the temporal dead zone

All three declarations are hoisted to the top of their scope, but they behave differently before the line that declares them. A var exists and holds undefined. A let or const exists but cannot be touched until its declaration runs. That gap is called the temporal dead zone.


_10
console.log(count); // undefined, a silent bug
_10
var count = 5;
_10
_10
console.log(total); // ReferenceError: Cannot access 'total' before initialization
_10
let total = 5;

The error is the better outcome. It points straight at the problem instead of letting undefined travel through your code.

Reassignment and redeclaration

const cannot be reassigned. let can. Neither can be declared twice in the same scope, while var happily lets you redeclare a name and overwrite it without warning.


_10
const limit = 10;
_10
limit = 20; // TypeError: Assignment to constant variable.
_10
_10
var name = "Ada";
_10
var name = "Grace"; // no error, the first value is gone

How to fix it

#

Default to const

Most variables are assigned once. Declaring them with const tells the reader the binding will not change, so they can stop tracking it. If you later need to reassign it, the error tells you exactly where, and you change that one declaration to let.


_10
const user = await getUser(id);
_10
const fullName = `${user.firstName} ${user.lastName}`;

Use let for counters, accumulators and flags

Reach for let when the value genuinely changes over time.


_10
let total = 0;
_10
for (const item of cart) {
_10
total += item.price * item.quantity;
_10
}

Notice that the loop variable is const. In a for...of loop each iteration gets a fresh binding, so const works. In a classic for (let i = 0; ...) loop you need let, because i is incremented.

Replace var in old code

When you touch legacy code, swapping var for let or const is usually safe, but check two cases first: code that reads the variable before its declaration, and code that relies on the variable being visible outside a block. Both will now throw, which is what you want to find out about.

ESLint can enforce all of this with the no-var and prefer-const rules.

Common pitfalls

#
  • const does not make values immutable. It stops you reassigning the variable, not changing the object it points to. const settings = { theme: "dark" } still allows settings.theme = "light". Use Object.freeze() if you need a shallow read-only object.
  • The classic loop and closure bug. With var, every callback created in a loop shares one variable, so they all see its final value. let creates a new binding per iteration.

_10
for (var i = 0; i < 3; i++) {
_10
setTimeout(() => console.log(i)); // 3, 3, 3
_10
}
_10
_10
for (let j = 0; j < 3; j++) {
_10
setTimeout(() => console.log(j)); // 0, 1, 2
_10
}

  • Top-level var in a classic script creates a global property. A var at the top of a non-module script becomes a property of window. let and const do not, and in ES modules nothing at the top level is global.
  • switch cases share one block. Declaring the same let name in two case clauses throws a SyntaxError. Wrap each case body in its own curly braces.
  • typeof is not safe in the temporal dead zone. typeof x normally returns "undefined" for unknown names, but throws if x is a let or const that has not been initialised yet.
#

quick question

Was this resource helpful?