TypeError: Assignment to constant variable
TypeError: invalid assignment to const 'x'
You declared a variable with const and then tried to reassign it. const means the binding can’t change.
Fix 1: Use let Instead
// ❌ Reassigning a const
const count = 0;
count = count + 1; // 💥
// ✅ Use let for variables that change
let count = 0;
count = count + 1;
Fix 2: Mutating Objects Is Fine
// ✅ const prevents reassignment, not mutation
const user = { name: 'Alice' };
user.name = 'Bob'; // ✅ This works — you're mutating, not reassigning
// ❌ But you can't reassign the variable
const user = { name: 'Alice' };
user = { name: 'Bob' }; // 💥 Assignment to constant
Fix 3: Array Push Is Fine, Reassignment Isn’t
// ✅ Mutating the array
const items = [1, 2, 3];
items.push(4); // ✅ Works
// ❌ Reassigning the array
const items = [1, 2, 3];
items = [1, 2, 3, 4]; // 💥
Fix 4: Loop Variable
// ❌ Using const in a loop that reassigns
const i = 0;
while (i < 10) {
i++; // 💥
}
// ✅ Use let
let i = 0;
while (i < 10) {
i++;
}
// ✅ const works in for...of (new binding each iteration)
for (const item of [1, 2, 3]) {
console.log(item); // ✅ Works
}
Fix 5: Accidental Redeclaration
// ❌ Importing and then reassigning
const express = require('express');
express = require('other-thing'); // 💥
// ✅ Use a different variable name
const express = require('express');
const other = require('other-thing');
When to Use const vs let
// Use const by default — it signals "this won't change"
const API_URL = 'https://api.example.com';
const config = { port: 3000 };
// Use let only when you need to reassign
let retries = 3;
let currentPage = 1;