Sub topic 7
Redeclaring and Reassigning Variables
This chapter assumes you can already declare variables with var, let, and const, and that you know the difference between function scope and block scope from the earlier chapters. You should also be comfortable with try...catch and running code in Node.js or a browser console.
Two operations are easy to confuse:
- Redeclaration means writing a second declaration for a name that already exists in the same scope, such as
var afollowed by anothervar a. - Reassignment means giving an existing binding a new value with
=,+=,++, or a destructuring assignment.
The three keywords handle these operations differently, and they fail at different times. A bad redeclaration is a SyntaxError that stops the whole script before any of it runs. A bad reassignment is a TypeError thrown at runtime, at the line where it happens. Once you know which is which, the error messages tell you what went wrong.
The rules at a glance
| Keyword | Redeclare in same scope | Reassign | Must initialize | Error when you break a rule |
|---|---|---|---|---|
| `var` | Allowed | Allowed | No | None |
| `let` | `SyntaxError` | Allowed | No | `SyntaxError` before the code runs |
| `const` | `SyntaxError` | `TypeError` | Yes | `SyntaxError` before the code runs, or `TypeError` at runtime |
Redeclaring with var
var lets you declare the same name as many times as you like in one function or script. All the declarations refer to one binding. This made sense in early JavaScript, where scripts were often pasted together from different sources.
var a = 1;
var a = 2; // allowed: same binding, new value
console.log(a); // 2
var a; // a declaration with no initializer does not reset the value
console.log(a); // 2The last line surprises people. Because of hoisting, var a; without = something is only a declaration, and the binding already exists, so it does nothing. The value stays 2 and is not reset to undefined.
The danger is that a silent redeclaration can overwrite a value you still need:
function totalPrice(items) {
var total = 0;
for (var i = 0; i < items.length; i++) {
total += items[i].price;
}
// Fifty lines later, someone adds this:
var total = items.length > 3 ? 0.9 : 1; // meant to be a discount factor
return total; // returns the factor, not the price
}
console.log(totalPrice([{ price: 10 }, { price: 20 }])); // 1Nothing warns you. The second var total reuses the first binding and replaces the sum. With let, the same mistake would fail before the program started.
Redeclaring with let and const
let and const reject a second declaration of the same name in the same scope. The check happens when the engine parses the code. This kind of error is called an early error: it is reported before the first line runs, so a script with one of these mistakes produces no output at all.
To show this in a runnable example, the code below hands the bad source to eval, which parses it at runtime and lets us catch the resulting SyntaxError:
const attempts = [
'let b = 1; let b = 2;',
'const c = 1; const c = 2;',
'let d = 1; var d = 2;',
'var e = 1; let e = 2;',
'let f = 1; { var f = 2; }',
];
for (const source of attempts) {
try {
eval(source);
console.log('ran:', source);
} catch (err) {
console.log(err.name + ':', source);
}
}
// SyntaxError: let b = 1; let b = 2;
// SyntaxError: const c = 1; const c = 2;
// SyntaxError: let d = 1; var d = 2;
// SyntaxError: var e = 1; let e = 2;
// SyntaxError: let f = 1; { var f = 2; }The rule is that a name can be declared at most once in a scope if any of those declarations uses let or const. Mixing keywords does not get around it. The last case is the subtle one. The var f sits inside a block, but var belongs to the enclosing function or script. It lands in the same scope as let f and conflicts with it.
In Node.js the message looks like SyntaxError: Identifier 'b' has already been declared. The message names the identifier, so you can search for its other declaration.
Shadowing is not redeclaration
Declaring the same name in a nested scope is allowed. The inner binding shadows the outer one: inside the inner block, the name refers to the inner binding, and the outer one is untouched.
let level = 'outer';
{
let level = 'inner'; // a new binding in a new block scope
console.log(level); // 'inner'
}
console.log(level); // 'outer'
function report(level) { // a parameter is also a new scope
return 'level is ' + level;
}
console.log(report('param')); // 'level is param'Shadowing is legal, but it can still confuse readers. Linters such as ESLint have a no-shadow rule if your team wants to forbid it.
Edge cases that trip people up
Function parameters
Parameters count as declarations in the function's scope. A let or const with the same name at the top of the function body is a redeclaration. A var with that name is allowed and refers to the parameter.
function withVar(x) {
var x; // allowed: same binding as the parameter
return x;
}
console.log(withVar(7)); // 7
try {
eval('(function withLet(x) { let x = 1; })');
} catch (err) {
console.log(err.name); // 'SyntaxError'
}
function withBlock(x) {
{
let x = 'shadow'; // allowed: a nested block is a new scope
console.log(x); // 'shadow'
}
return x;
}
console.log(withBlock(7)); // 'shadow' then 7switch statements
All the case clauses of a switch share one block. Two cases that each declare let message are a redeclaration:
function describe(code) {
switch (code) {
case 200: {
const message = 'OK';
return message;
}
case 404: {
const message = 'Not Found'; // fine: each case has its own braces
return message;
}
default:
return 'Unknown';
}
}
console.log(describe(404)); // 'Not Found'If you remove the braces around each case body, the parser reports Identifier 'message' has already been declared. Wrapping each case in { } gives it its own block scope.
Separate scripts and the console
In a browser, classic <script> tags share one global scope for let and const. If one script declares let user at the top level and a later script does the same, the second script fails with a SyntaxError and none of it runs. ES modules avoid this because each module has its own top-level scope.
Reassigning variables
Reassignment uses an existing binding. var and let both allow it, with any assignment operator:
let score = 10;
score = 15; // plain assignment
score += 5; // compound assignment
score++; // increment
console.log(score); // 21
let x = 1;
let y = 2;
[x, y] = [y, x]; // destructuring assignment swaps the values
console.log(x, y); // 2 1
let width, height;
({ width, height } = { width: 640, height: 480 }); // parentheses required
console.log(width, height); // 640 480The parentheses in the last assignment matter. Without them, the parser reads { width, height } at the start of a statement as a block, and = ... after a block is a SyntaxError.
Note that the swap line has no keyword. Writing let [x, y] = [y, x] would be a redeclaration, and therefore an error.
Reassigning const
A const binding must be initialized when it is declared, and it can never be assigned again. The two rules fail in different ways:
try {
eval('const missing;');
} catch (err) {
console.log(err.name); // 'SyntaxError': const needs an initializer
}
const limit = 10;
try {
limit = 20;
} catch (err) {
console.log(err.name, '-', err.message);
// 'TypeError - Assignment to constant variable.' (Node.js / V8 wording)
}
try {
limit += 1; // compound assignment is still assignment
} catch (err) {
console.log(err.name); // 'TypeError'
}
console.log(limit); // 10Unlike many silent failures in JavaScript, assigning to a const throws in both strict and sloppy mode. But it throws only when that line runs. A bad assignment buried in a rarely used branch can sit unnoticed until production. Linters catch it ahead of time with ESLint's no-const-assign rule, and TypeScript reports it as a compile error.
const in loops
Whether const works as a loop variable depends on the kind of loop:
for (const name of ['Ada', 'Lin']) {
console.log(name); // works: each iteration gets a fresh binding
}
for (const key in { a: 1, b: 2 }) {
console.log(key); // works for the same reason
}
try {
for (const i = 0; i < 3; i++) {
console.log('iteration', i); // prints 'iteration 0' once
}
} catch (err) {
console.log(err.name); // 'TypeError' thrown by i++
}for...of and for...in create a new binding on every iteration and never assign to an existing one, so const is fine. A classic for loop updates its counter with i++, which is a reassignment. The body runs once, and then the update throws. Use let for counters.
Common errors and their causes
| Message (V8 wording) | Error | Cause | Fix |
|---|---|---|---|
| `Identifier 'x' has already been declared` | `SyntaxError` | Second declaration of `x` in a scope that has a `let` or `const` `x` | Remove the keyword to reassign, or rename one of them |
| `Missing initializer in const declaration` | `SyntaxError` | `const x;` | Give it a value, or use `let` |
| `Assignment to constant variable.` | `TypeError` | `=`, `+=`, `++`, or destructuring targets a `const` | Use `let` if the value really changes, or create a new `const` |
| No error, wrong value | None | Duplicate `var` overwrote a value | Switch to `let` or `const` so the parser catches it |
A useful reading of this table: the SyntaxError cases tell you the structure of your code is wrong, so look for a duplicate name. The TypeError tells you the code is valid but tried to do something the binding forbids, so look at the line in the stack trace.
Exercises
Exercise
What does this code print, and why? var n = 5; var n; console.log(n);
Show answer
It prints 5. The second var n has no initializer, so it only redeclares the existing binding, which var allows. The value stays 5 and is not reset to undefined.
Exercise
A file contains let count = 0; on line 1, console.log('start'); on line 2, and let count = 1; on line 40. Does 'start' get printed? Explain.
Show answer
No. Redeclaring a let binding in the same scope is an early SyntaxError. The engine reports it while parsing the file, before any statement runs, so line 2 never executes.
Exercise
Is function f(value) { { let value = 2; } return value; } valid, and what does f(1) return?
Show answer
It is valid. The let is inside a nested block, so it shadows the parameter and does not redeclare it. After the block ends, value refers to the parameter again, so f(1) returns 1.
Exercise
Why does for (const i = 0; i < 3; i++) { console.log(i); } print 0 and then throw, while for (const v of [0, 1, 2]) works?
Show answer
The classic for loop reassigns its counter with i++ after each iteration. That is an assignment to a const, so it throws a TypeError after the first body run. for...of creates a fresh binding for each element and never reassigns it, so const is allowed.
Exercise
Fix this so it swaps the values without an error: let a = 1; let b = 2; let [a, b] = [b, a];
Show answer
Remove the keyword from the last statement: [a, b] = [b, a];. With let, the line redeclares a and b, which is a SyntaxError. Without it, it is a destructuring reassignment of the existing bindings.