BugHunt

TypeError: Assignment to constant variable.

You reassigned a name declared with const. Use let if the binding genuinely needs to change.

JavaScriptScope and closure bugs

What it means

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.

Common causes

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.

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.

Other common errors