Sub topic 12
Which Keyword Should You Use?
The earlier chapters covered how var, let, and const behave. This chapter turns those rules into a practical habit. It assumes you have read them and can explain block scope versus function scope, the temporal dead zone (TDZ), the difference between a const binding and an immutable value, the loop-closure bug, and how top-level var creates properties on globalThis. You should also be comfortable reading for loops, switch statements, and small functions.
Here is the rule most modern style guides and teams follow:
- Use
constby default. - Use
letwhen the variable must be reassigned. - Do not use
varin new code.
The rest of this chapter explains why the rule works, how to apply it in awkward cases, how to convert old var code without breaking it, and how to make tooling enforce the rule for you.
Why const comes first
const tells the reader something useful: this name points at the same value for the whole of its scope. The reader can see the declaration and stop checking for later assignments. With let, the reader has to scan the rest of the block for reassignments before they know what the variable holds.
const also turns an accidental reassignment into an immediate error rather than a silent bug:
const taxRate = 0.2;
function priceWithTax(price) {
try {
taxRate = 0.25; // typo or misguided "quick fix"
} catch (e) {
console.log(e.name); // 'TypeError'
}
return price * (1 + taxRate);
}
console.log(priceWithTax(100)); // 120If taxRate had been declared with let, the assignment would have succeeded and changed the result of every later call.
In practice most variables are never reassigned. Function results, configuration objects, imported modules, DOM elements, and intermediate calculations are usually assigned once. Declaring them with const makes the few variables that do change easy to spot, because those are the only ones declared with let.
When let is the right choice
Use let when the variable's job requires a new value to be assigned to it. The common cases are:
- Counters and accumulators that change inside a loop.
- Classic
forloop indexes, which are incremented. - Values that are assigned in different branches after the declaration.
- Variables updated inside a
try/catchand read afterwards. - State held in a closure, such as a running total.
function summarize(scores) {
let total = 0;
let best = -Infinity;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
if (scores[i] > best) best = scores[i];
}
return { total, best };
}
console.log(summarize([4, 9, 2])); // { total: 15, best: 9 }Sometimes let shows up only because the value is chosen by an if statement. You can often keep const by computing the value in one expression:
const hour = 14;
// Version with let: the declaration and the assignment are separated
let greetingA;
if (hour < 12) {
greetingA = 'Good morning';
} else {
greetingA = 'Good afternoon';
}
// Version with const: a single expression
const greetingB = hour < 12 ? 'Good morning' : 'Good afternoon';
console.log(greetingA === greetingB); // trueFor more than two branches, move the logic into a small function and assign its return value to a const. Do not force this when it makes the code harder to read. A clear let is better than a convoluted chain of ternaries.
Where var still appears
var remains valid JavaScript and will keep working, but it has no advantage in new code that let or const cannot provide. You will still run into it in these places:
- Legacy code written before ES2015, or by developers who learned JavaScript then.
- Transpiled output. Tools that target very old engines may emit
var. This is generated code and you do not edit it by hand. - Classic scripts that deliberately create globals. A top-level
varin a non-module script becomes a property ofglobalThis. If code really needs a global, writingglobalThis.appConfig = ...states that intent more clearly.
The one behavior that only var gives you is function-wide visibility of a variable declared inside a block. That is the behavior that caused the loop-closure bug and the confusing hoisting results from earlier chapters, so losing it is the goal.
A decision flowchart
Side-by-side summary
| Property | `const` | `let` | `var` |
|---|---|---|---|
| Scope | Block | Block | Function (or global) |
| Access before declaration | ReferenceError (TDZ) | ReferenceError (TDZ) | `undefined` |
| Redeclare in same scope | SyntaxError | SyntaxError | Allowed |
| Reassign | TypeError | Allowed | Allowed |
| Must initialize | Yes | No | No |
| New binding per `for` iteration | Yes (in `for...of`/`for...in`) | Yes | No, one shared binding |
| Top-level in classic script adds `globalThis` property | No | No | Yes |
| Recommended for new code | Default | When reassigned | No |
Common mistakes when applying the rule
Using const as a classic for loop index
const works in for...of and for...in loops because each iteration gets a fresh binding that is never reassigned. A classic for loop increments its index, so const fails there:
const items = ['a', 'b', 'c'];
for (const item of items) {
console.log(item); // a, b, c — fine
}
try {
for (const i = 0; i < items.length; i++) {
console.log(items[i]); // prints 'a' once
}
} catch (e) {
console.log(e.name); // 'TypeError' thrown by i++
}The body runs once before the increment throws. Use let for the index, or switch to for...of when you do not need it.
Declaring everything at the top of the function
With var, programmers often moved all declarations to the top of the function to match hoisting. With let and const you should declare a variable close to where it is first used and in the smallest block that needs it. This keeps scopes small and lets the TDZ catch code that uses a variable too early.
Colliding declarations in switch cases
All case clauses in a switch share one block. Two const label declarations in different cases are a redeclaration in the same scope, which is a SyntaxError. Give each case its own block with braces:
function describe(kind) {
switch (kind) {
case 'a': {
const label = 'first';
return label;
}
case 'b': {
const label = 'second';
return label;
}
default:
return 'unknown';
}
}
console.log(describe('a'), describe('b'), describe('z')); // first second unknownTreating const as a promise of immutability
A teammate may read const settings = {...} and assume no code changes settings.debug. That assumption is wrong. If the contents matter, freeze the object or document that it is mutable.
Using let "just in case"
Declaring with let in case you need to reassign later removes the signal const gives readers. Start with const. If you later need reassignment, the TypeError, or your linter, will tell you, and changing the keyword takes a second.
Converting var to let and const safely
Swapping var for let with find-and-replace usually works, but it can break code that depends on var semantics. Look for these hazards first:
- Use outside the block. A variable declared in a loop or
ifwithvarand read after that block. - Use before the declaration. Code that reads a
varbefore its declaration line and relies on gettingundefined. Withletthis throws a ReferenceError. - Redeclaration. Two
varstatements for the same name in one function. Withletthis is a SyntaxError. - Global property access. Other scripts reading
window.someNameorglobalThis.someNamefor a top-levelvar. - Closures in loops. Here the conversion changes behavior on purpose. Callbacks will now capture each iteration's value. That is usually the fix you want, but check that nothing depended on the old result.
This function relies on the loop variable leaking out of the loop:
function indexOfTarget(items, target) {
for (var i = 0; i < items.length; i++) {
if (items[i] === target) break;
}
return i < items.length ? i : -1; // reads i after the loop
}
console.log(indexOfTarget(['x', 'y', 'z'], 'y')); // 1Changing var to let makes i exist only inside the loop, so the return line throws ReferenceError: i is not defined. The fix is to declare the variable in the scope where it is actually used:
function indexOfTarget(items, target) {
let i;
for (i = 0; i < items.length; i++) {
if (items[i] === target) break;
}
return i < items.length ? i : -1;
}
console.log(indexOfTarget(['x', 'y', 'z'], 'y')); // 1
console.log(indexOfTarget(['x', 'y', 'z'], 'q')); // -1A process that works well for larger files:
- Run the existing tests, or write a few quick ones if there are none.
- Change each
vartolet. - Fix any SyntaxError or ReferenceError by moving declarations to the right scope.
- Change each
letthat is never reassigned toconst. - Run the tests again and search the codebase for global-object access to any converted top-level names.
Letting tooling enforce the rule
You do not need to apply this rule by memory. ESLint has built-in rules for it:
no-varreports everyvardeclaration.prefer-constreports aletthat is never reassigned, and can fix it automatically.no-undefreports use of undeclared names, which catches accidental globals before runtime.
A minimal flat configuration file (eslint.config.js) looks like this:
export default [
{
files: ['**/*.js'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
console: 'readonly',
},
},
rules: {
'no-var': 'error',
'prefer-const': 'error',
'no-undef': 'error',
},
},
];Running npx eslint --fix . converts unchanged let declarations to const. ESLint's autofix for no-var only rewrites declarations it can prove are safe, so expect to handle some var cases by hand using the hazard list above.
Exercises
Exercise
For each variable below, choose const or let and explain why: (1) a variable holding the result of document.querySelector('#form'); (2) a running sum updated inside a forEach callback; (3) the loop variable in for (___ user of users); (4) the index in for (___ i = 0; i < n; i++).
Show answer
(1) const, because the element reference is assigned once (you may still change the element's properties). (2) let, because sum += x reassigns it. (3) const, because for...of creates a fresh binding per iteration that is never reassigned. (4) let, because i++ reassigns the index; const would throw a TypeError on the first increment.
Exercise
A legacy function contains if (debug) { var log = []; } ... if (debug) { log.push('done'); }, where the two if statements are separate blocks. What happens if you replace var with let, and how do you fix it?
Show answer
With let, log exists only inside the first if block, so log.push in the second block throws a ReferenceError (or resolves to an unrelated outer log). Fix it by declaring let log; (or const log = debug ? [] : null;) in the function scope before both if statements, so both blocks can see the same binding.
Exercise
A teammate argues: "We should use let everywhere because const doesn't make objects immutable anyway, so it gives no real protection." Give two reasons this argument is wrong.
Show answer
First, const does protect something real: the binding. Accidental reassignment throws a TypeError instead of silently changing the variable. Second, const tells readers that the name always refers to the same value, so the remaining let declarations clearly mark the variables that change. When the contents also need protection, combine const with Object.freeze or non-mutating code. Using let everywhere loses both benefits and gains nothing.