How to Fix TypeError: Assignment to constant variable in JavaScript
In this tutorial, you'll learn about How to Fix TypeError: Assignment to constant variable in JavaScript. We cover key concepts, practical examples, and best practices.
The Problem
JavaScript throws TypeError: Assignment to constant variable when you try to reassign a variable declared with const, which cannot be reassigned after its initial assignment.
Quick Fix
Step 1: Change const to let
If the variable needs to be reassigned, use let:
const count = 0;
count = count + 1;
TypeError: Assignment to constant variable.
Change to let:
let count = 0;
count = count + 1;
console.log(count);
1
Step 2: Use const for immutable references only
const prevents reassignment of the variable binding, not mutation of the value:
const user = { name: 'Alice' };
user = { name: 'Bob' };
TypeError: Assignment to constant variable.
Instead, mutate the object properties:
const user = { name: 'Alice' };
user.name = 'Bob';
console.log(user);
{ name: 'Bob' }
Step 3: Check for accidental reassignment in loops
Reassigning a loop variable declared with const throws:
const items = [1, 2, 3];
for (const item of items) {
item = item * 2;
}
TypeError: Assignment to constant variable.
Use a different variable for the modified value:
const items = [1, 2, 3];
for (const item of items) {
const doubled = item * 2;
console.log(doubled);
}
2
4
6
Step 4: Avoid redeclaring parameters
Trying to reassign function parameters declared with const:
function process(value) {
const value = value * 2;
return value;
}
SyntaxError: Identifier 'value' has already been declared
Use a different variable name:
function process(value) {
const result = value * 2;
return result;
}
console.log(process(5));
10
Prevention
- Use
constby default and switch toletonly when reassignment is needed. - Prefer immutable data patterns: create new objects/arrays instead of mutating.
- Use ESLint
no-const-assignrule to catch these errors at lint time. - Treat
constvariables as final bindings to signal intent to other developers.
Common Mistakes with const assign
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro