🔧 Error Fixes
· 1 min read

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) {}