πŸ”§ 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: TypeError: Cannot Read Properties of Null β€” How to Fix It (Vanilla JS)