Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Variable defined with a reserved word const can be changed - JavaScript?
In JavaScript, variables declared with const cannot be reassigned, but this doesn't mean the contents of objects or arrays are immutable. You can still modify the properties of objects declared with const.
Understanding const with Objects
The const keyword prevents reassignment of the variable itself, but object properties can still be modified:
const details = {
firstName: 'David',
subjectDetails: { subjectName: 'JavaScript' }
};
// This works - modifying object properties
details.firstName = 'John';
details.subjectDetails.subjectName = 'Python';
console.log(details);
{ firstName: 'John', subjectDetails: { subjectName: 'Python' } }
What const Actually Prevents
You cannot reassign the entire object, but you can modify its contents:
const details = {
firstName: 'David',
subjectDetails: { subjectName: 'JavaScript' }
};
// This will throw an error - reassigning the variable
try {
details = { firstName: 'Alice' };
} catch (error) {
console.log('Error:', error.message);
}
// This works - modifying properties
details.firstName = 'Bob';
console.log('Modified object:', details);
Error: Assignment to constant variable.
Modified object: { firstName: 'Bob', subjectDetails: { subjectName: 'JavaScript' } }
Creating Immutable Copies
If you want to create a new object without modifying the original, use the spread operator:
const details1 = {
firstName: 'David',
subjectDetails: { subjectName: 'JavaScript' }
};
// Create a deep copy to avoid modifying the original
const details2 = {
...details1,
subjectDetails: { ...details1.subjectDetails },
firstName: 'Alice'
};
details2.subjectDetails.subjectName = 'Java';
console.log('Original:', details1);
console.log('Copy:', details2);
Original: { firstName: 'David', subjectDetails: { subjectName: 'JavaScript' } }
Copy: { firstName: 'Alice', subjectDetails: { subjectName: 'Java' } }
Key Points
-
constprevents variable reassignment, not object mutation - Object properties can still be modified after declaration
- Use spread operator or
Object.freeze()for true immutability - Arrays declared with
constfollow the same rules
Conclusion
The const keyword in JavaScript prevents reassignment of the variable itself, but allows modification of object properties. For true immutability, use techniques like the spread operator or Object.freeze().
Advertisements
