Brainlag
  1. Library
  2. Debugging
  3. Web

Assignment to constant variableWhat is "Assignment to constant variable"?

This TypeError means a line tried to give a const variable a new value. Use let for anything that has to change.

Web5 min

What JavaScript is telling you

Output
TypeError: Assignment to constant variable.

A variable made with const can never be pointed at a new value. Any line that tries (=, +=, -=, ++) stops the program with this error.

JavaScript
const score = 0;
score += 10;   // TypeError

The fix is almost always to swap const for let where the variable is created. Changing what is inside a const array or object is fine, though: const team = []; team.push("Ana"); works, because team still points at the same array.

How to find it

The message does not name the variable, so use the line number. Find the =, += or ++ on that line, note the variable, then search upwards for where it was created. If it says const and the value really needs to change, make it let. If it should never change, the bug is the line trying to change it.

Run it: the lives counter

Press Run and read the error from the bottom up.

main.js to run
const lives = 3;
console.log("Lives:", lives);

lives = lives - 1;
console.log("Lives:", lives);

A coin counter that crashes

Each pickup adds coins. This should print Coins: 65. Fix it, and keep const on anything that does not change.

Constraint

  • Keep pickups as a const: the array itself never changes.
exercise_1.js to run
const pickups = [10, 25, 5, 25];
const coins = 0;
for (const value of pickups) {
  coins += value;
}
console.log("Coins: " + coins);

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.