TypeError: Assignment to constant variable.
TypeError: Assignment to constant variable. in JavaScript means you reassigned a name declared with const. Use let if the binding genuinely needs to change.
How do I fix TypeError: Assignment to constant variable.?
TypeError: Assignment to constant variable means you reassigned a name declared with const. Common cases are for (const i = 0; i < n; i++), total += x on a const, or arr = arr.filter(...). Change the declaration to let when the value must change, or store the new value in a new const, like const remaining = todos.filter(...).
- 1. Find the reassigning lineThe stack trace points at the line with =, +=, ++ or --. Find that name's const declaration.
- 2. Check for loop countersfor (const i = 0; ...; i++) fails on the first increment. Use let i.
- 3. Prefer a new constInstead of reassigning, give the new value its own name, or use reduce for running totals.
What does TypeError: Assignment to constant variable. mean?
const fixes the binding, not the value: you cannot point the name at something new, but you can still change the contents of a const object or array. So `const list = []; list.push(1)` is fine, while `list = [1]` throws. This error only happens at run time, on the line that reassigns.
Why does TypeError: Assignment to constant variable. happen?
1. A const loop counter
i++ reassigns i. The first iteration runs, then the increment throws.
Breaks
for (const i = 0; i < 5; i++) {
console.log(i);
}Works
for (let i = 0; i < 5; i++) {
console.log(i);
}2. An accumulator declared with const
total += x is reassignment.
Breaks
const total = 0;
for (const x of nums) total += x;Works
const total = nums.reduce((sum, x) => sum + x, 0);3. Replacing an array instead of changing it
Filtering returns a new array, and assigning it reassigns the const.
Breaks
const todos = load();
todos = todos.filter(t => !t.done);Works
const todos = load();
const remaining = todos.filter(t => !t.done);How to find it in your own code
Keep const as the default and switch to let only for names that must change — the error is useful, it points at every place a value changes. Often the better fix is a new const with a more precise name, as in the last example.
Try it: fix this bug
easycountPositives([3, -1, 4]) throws TypeError: Assignment to constant variable.
function countPositives(nums) {
const count = 0;
for (const n of nums) {
if (n > 0) {
count++;
}
}
return count;
}Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.