Assignment to Constant Variable: What It Means and How to Fix It
Error reference
Assignment to Constant Variable
Language
Severity
MediumWhen it happens
This TypeError is thrown at runtime when you attempt to reassign a variable declared with const.
Potential fixes
Use let for variables whose values will change. Reserve const for values that are truly fixed. Remember that const objects can still have their properties mutated; use Object.freeze() if you need true immutability.
Related errors
Deep dive
This TypeError is thrown at runtime when you attempt to reassign a variable declared with const. const creates a binding that cannot be reassigned after initialization. Note that for objects and arrays, the binding is constant but the contents can still be mutated.
Why it happens
- •Directly reassigning a const variable with = after its initial declaration.
- •Using += or ++ on a const variable.
- •Accidentally declaring a loop counter with const instead of let.
- •Mistakenly thinking const makes a full deep-freeze of objects.
Potential fixes
Use let for variables whose values will change. Reserve const for values that are truly fixed. Remember that const objects can still have their properties mutated; use Object.freeze() if you need true immutability.
Examples
Code that triggers the error
const MAX_RETRIES = 3;
MAX_RETRIES = 5;Error output
TypeError: Assignment to constant variable.
Fixed code
// Use let if the value needs to change
let maxRetries = 3;
maxRetries = 5;
// Or keep const if the value is truly fixed
const MAX_RETRIES = 3;Practice in English
How would you explain an Assignment to Constant Variable to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free