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;
Related resources
Related: JavaScript Array Methods Cheat Sheet