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.
Examples
Code that triggers the error
const MAX_RETRIES = 3;
MAX_RETRIES = 5;Error output
TypeError: Assignment to constant variable.
How to fix it
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.
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;Related errors
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