Assignment to constant variable
An attempt was made to reassign a value to a variable declared with const.
Usually happens because:
- ☑ Reassigned const variable
- ☑ Const loop iterator
- ☑ Comparison typo (= instead of ===)
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Assignment to constant variable?
This TypeError is thrown when you attempt to change the reference of a variable declared with the const keyword. Const declarations create read-only references to values. You cannot reassign them (e.g. const x = 5; x = 6;). Note that for objects declared with const, you can still modify their properties (like const obj = {}; obj.name = 'John'), but you cannot reassign the object itself.
Common Causes
- Reassigning const variables in loops (e.g. inside for loops).
- Accidentally reusing variable names declared with const.
- Typing reassignment operators (=) instead of comparison operators (===) on const variables.
Common Mistakes
- Assuming const variables protect object keys from modification (objects fields can always be modified; only the primary variable reference is constant).
How to Fix
Framework-Specific Examples
Declaring loop counters using const instead of let.
try {
// Throws error on first loop increment
for (const i = 0; i < 5; i++) {
console.log(i);
}
} catch (err) {
console.error(err.message); // Assignment to constant variable.
}Server Configuration Examples
Checking variable scopes.
# Handled at code levelBest Practices
- Use let by default if you expect variables to change their values.
- Use Object.freeze(obj) to make object structures completely immutable.
Frequently Asked Questions (FAQ)
Q: Can I change properties of a const object?
Yes. Const only prevents reassignment of the variable name identifier to a new reference. You can add, delete, or change properties of arrays and objects declared with const.
Q: Should I use let or const?
Use const by default for all variables that do not require reassignment. This makes your intent clear and prevents accidental reassignments. Use let only when values must be updated.
Q: What is the difference between let, const, and var?
Var has function scope, can be redeclared, and is hoisted. Let has block scope and cannot be redeclared. Const has block scope, cannot be redeclared, and cannot be reassigned.
Q: Does Object.freeze prevent property modification?
Yes. Calling `Object.freeze(obj)` prevents properties from being added, deleted, or updated, making the object immutable.