Sub topic 12
Which Keyword Should You Use?
This chapter assumes you have read the earlier chapters on scope, hoisting, the temporal dead zone, redeclaration, const bindings, loop closures, and globals. It does not re-explain those rules. It turns them into one decision you can make every time you declare a variable.
The Modern Default
Most current style guides and linters agree on three rules:
- Use
constby default. - Use
letonly when the variable must be reassigned. - Do not use
varin new code.
The reason for this order is that each keyword tells the reader something. const says "this name always points to the same thing." let says "watch this name, its value will change." var says very little, because it can be redeclared, it leaks out of blocks, and it reads as undefined before its declaration runs.
Why `const` First
const limits what can happen to a name. When you read a 40-line function and see const user = ..., you know user is never reassigned anywhere below. You don't have to scan for later assignments. If you later try to reassign it by mistake, you get a TypeError at runtime instead of a silent bug.
Remember that const freezes the binding, not the value. A const array can still be pushed to. That is usually what you want. Reach for Object.freeze only when you need the contents to be read-only as well.
When `let` Is the Right Choice
Use let when the name truly has to change:
- Counters and accumulators, such as
let total = 0. - Classic
for (let i = 0; ...)loops, where each iteration gets a fresh binding. - Values assigned in different branches before they are used.
If you notice a let that is assigned only once, change it to const.
Where `var` Still Appears
You will still find var in older code, in some build tool output, and in classic scripts that deliberately create a property on globalThis. In new code, let or const covers every case.
The Decision at a Glance
| Keyword | Scope | Reassign | Redeclare | Before declaration |
|---|---|---|---|---|
| `const` | Block | No (TypeError) | No (SyntaxError) | ReferenceError (TDZ) |
| `let` | Block | Yes | No (SyntaxError) | ReferenceError (TDZ) |
| `var` | Function | Yes | Yes | `undefined` |
Worked Example: Modernizing a Function
Here is a function written in the old style, followed by the same logic using the modern rules.
// Before: everything is var
function summarize(orders) {
var label = 'Orders';
var total = 0;
for (var i = 0; i < orders.length; i++) {
var price = orders[i].price;
total += price;
}
return label + ': ' + total;
}
// After: const by default, let only where reassignment happens
function summarizeModern(orders) {
const label = 'Orders';
let total = 0;
for (const order of orders) {
const price = order.price;
total += price;
}
return `${label}: ${total}`;
}
const orders = [{ price: 5 }, { price: 7 }];
console.log(summarize(orders)); // Orders: 12
console.log(summarizeModern(orders)); // Orders: 12Only total changes, so it is the only let. const order works inside for...of because each iteration creates a new binding. In the old version, i and price are still visible after the loop, while the modern version keeps them inside the loop.
Let a Linter Enforce It
You don't have to remember these rules by hand. ESLint has built-in rules for them. In a flat config file:
// eslint.config.js
export default [
{
rules: {
'no-var': 'error',
'prefer-const': 'error',
},
},
];no-var flags every var. prefer-const flags any let that is never reassigned, and eslint --fix can rewrite those automatically.
Common Mistakes
- Using
let"just in case." It hides which names actually change. Start withconstand switch toletonly when you need to reassign. - Thinking
constprotects data.const items = []still allowsitems.push(1). UseObject.freezeif you need the contents to be read-only. - Converting legacy
varblindly. See the warning above.
Exercise
Choose a keyword for each name and explain why: (1) retries, which starts at 0 and goes up inside a while loop; (2) settings, an object that is created once and later gets new properties added; (3) API_URL, a string that never changes.
Show answer
(1) let, because the name is reassigned when it is incremented. (2) const, because adding properties changes the object, not the binding, so the name is never reassigned. (3) const, because it is assigned once and never changes. None of them needs var.
Exercise
A teammate changes var count = 0; to let count = 0; at the top of an old classic script, and another script that reads window.count breaks. Why?
Show answer
In a classic script, a top-level var creates a property on the global object (window/globalThis). A top-level let does not, so window.count is now undefined. Either update the other script to share the value explicitly, or keep var until both scripts are refactored.