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. Here you will learn two separate rules that people often confuse:
- Redeclaration means writing a second declaration for a name that already exists in the same scope, for example
let xtwice. - Reassignment means giving an existing variable a new value with
=,+=,++, and similar operators.
Each keyword handles these two operations differently. The errors they produce also show up at different times.
The Rules at a Glance
| Keyword | Redeclare in same scope | Reassign | Must initialize |
|---|---|---|---|
| `var` | Allowed | Allowed | No |
| `let` | SyntaxError | Allowed | No |
| `const` | SyntaxError | TypeError | Yes (SyntaxError) |
Redeclaration
With var, a second declaration of the same name is ignored. If it has an initializer, that part runs as an ordinary assignment. This is how two pieces of code can quietly overwrite each other's variables.
var user = 'Ada';
var user = 'Grace'; // no error: same variable, new value
console.log(user); // 'Grace'let and const reject redeclaration. The check happens while the engine parses your code, so the whole script or module fails to start. None of its lines run, including lines above the duplicate. Because of that, you can't catch this error with a try block in the same script. The example below uses eval so the bad code is parsed separately and the error can be shown:
const attempts = [
'let b = 1; let b = 2;',
'var c = 1; let c = 2;',
'let d = 1; { var d = 2; }',
'const e;'
];
for (const code of attempts) {
try {
eval(code);
} catch (err) {
console.log(err.name, '-', code);
}
}
// SyntaxError - let b = 1; let b = 2;
// SyntaxError - var c = 1; let c = 2;
// SyntaxError - let d = 1; { var d = 2; }
// SyntaxError - const e;Two of these cases are easy to miss:
- Mixing
varandletfor the same name is a conflict, whichever comes first. - A
varinside a block still belongs to the enclosing function or script. So{ var d = 2; }collides with an outerlet d.
The last line shows that const must be initialized in its declaration. Leaving the value out is also a SyntaxError.
Shadowing Is Not Redeclaration
You can declare the same name again in a nested scope. The inner variable shadows the outer one, which means it hides the outer one while the inner block runs. The outer variable is left unchanged.
let level = 'outer';
{
let level = 'inner'; // a new variable, scoped to this block
console.log(level); // 'inner'
}
console.log(level); // 'outer'Reassignment
Code using var or let can reassign the variable whenever it likes. A const binding can never be reassigned. That covers plain =, compound operators like +=, and ++/--. The engine only finds the problem when the assignment runs, so the error is a runtime TypeError. You can catch it normally, and all the code before it has already run.
let score = 10;
score += 5; // fine
console.log(score); // 15
const max = 100;
console.log('before'); // this line runs
try {
max++;
} catch (err) {
console.log(err.name); // 'TypeError'
console.log(max); // 100, unchanged
}const throws this TypeError in both strict and sloppy mode. Some other failed assignments are silently ignored in sloppy mode, but this one always throws.
Common Mistakes
- Declaring a
constthat you later need to change. A counter or accumulator should uselet. - Declaring a name twice when you meant to assign it. Typing
let total = 0a second time instead oftotal = 0breaks the entire script. - Relying on
varredeclaration in large files. Two unrelated sections that both usevar iorvar resultshare a single variable without any warning.
The next chapter looks at what const really protects. It locks the binding, but not necessarily the value the binding holds.
Exercise
For each snippet, say whether it runs, throws a SyntaxError, or throws a TypeError: (1) var n = 1; var n = 2; (2) let n = 1; if (true) { let n = 2; } (3) const n = 1; n += 1; (4) function f(n) { let n = 2; }
Show answer
(1) Runs. var allows redeclaration, and n ends up as 2. (2) Runs. The inner let shadows the outer n in a nested block. (3) TypeError at runtime, because n += 1 reassigns a const. (4) SyntaxError, because the parameter n and the let n share the function's top-level scope.
Exercise
A script starts with console.log('start'); and later contains let id = 1; followed by let id = 2;. Does 'start' get printed? Why or why not?
Show answer
No. Redeclaring a let is a SyntaxError found when the script is parsed. The script never starts running, so no line executes, including the console.log above the duplicate.