π§ Error Fixes
Β· 1 min read
JavaScript TypeError: Assignment to Constant Variable β How to Fix It
TypeError: Assignment to constant variable
Youβre trying to reassign a variable declared with const.
Fix 1: Use let instead of const
// β Can't reassign const
const count = 0;
count = 1; // TypeError!
// β
Use let for values that change
let count = 0;
count = 1;
Fix 2: You can still mutate objects and arrays
const user = { name: 'Alice' };
// β Can't reassign the variable
user = { name: 'Bob' }; // TypeError!
// β
But you CAN modify properties
user.name = 'Bob'; // Works!
const items = [1, 2, 3];
items.push(4); // Works! Array is mutated, not reassigned
Fix 3: Loop variable
// β const in a for loop
for (const i = 0; i < 10; i++) {} // TypeError on i++
// β
Use let
for (let i = 0; i < 10; i++) {}
// β
const works in for...of (new variable each iteration)
for (const item of items) {}
Related resources
Related: TypeError: Cannot Read Properties of Null β How to Fix It (Vanilla JS)