🔧 Error Fixes

Fix: TypeError — Assignment to constant variable


TypeError: Assignment to constant variable.

You declared a variable with const and then tried to reassign it.

Fix 1: Use let instead of const

// ❌ Can't reassign a const
const count = 0;
count = 1;  // TypeError!

// ✅ Use let for values that change
let count = 0;
count = 1;

Fix 2: Mutate the object instead of reassigning

const prevents reassignment, not mutation. You can change properties of a const object:

const user = { name: "Alice" };

// ❌ Can't reassign the variable
user = { name: "Bob" };  // TypeError!

// ✅ Can change properties
user.name = "Bob";  // Fine!

const items = [];
// ❌ items = [1, 2, 3];  // TypeError!
// ✅ items.push(1, 2, 3);  // Fine!

Fix 3: Check for accidental reassignment in loops

// ❌ const in a reassigning loop
const i = 0;
while (i < 10) {
  i++;  // TypeError!
}

// ✅ Use let
let i = 0;
while (i < 10) {
  i++;
}

// ✅ const is fine in for...of (new variable each iteration)
for (const item of items) {
  console.log(item);  // Fine!
}

Rule of thumb

Use const by default. Switch to let only when you need to reassign. Never use var.

See also: JavaScript array methods cheat sheet