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.
What JavaScript is telling you
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.
const score = 0;
score += 10; // TypeErrorThe 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.
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.
const pickups = [10, 25, 5, 25];
const coins = 0;
for (const value of pickups) {
coins += value;
}
console.log("Coins: " + coins);