Mutability vs. Immutability in JavaScript
mutability and immutability refer to whether a value or data structure can be modified after it is created.
1. Mutable Data (Can Be Changed)
- Definition: Mutable data can be changed in place without creating a new copy.
- Examples: Objects and arrays are mutable.
Example of Mutable Data
let person = { name: "Ashik", age: 25 };
// Modifying the object (mutation)
person.age = 26;
console.log(person); // { name: "Ashik", age: 26 }
✅ The person object is modified directly.
2. Immutable Data (Cannot Be Changed)
- Definition: Immutable data cannot be modified once created. Instead, any change creates a new copy.
- Examples: Primitive types (strings, numbers, booleans) and immutable patterns in objects/arrays.
Example of Immutable Data (Primitives)
let name = "Ashik";
let newName = name.toUpperCase();
console.log(name); // "Ashik" (unchanged)
console.log(newName); // "ASHIK" (new string created)
✅ Strings are immutable, so .toUpperCase() returns a new string instead of modifying name.
3. Making Objects Immutable (Using Spread Operator)
To prevent modifying objects or arrays, you can create new copies instead of changing the original.
Immutable Object Update
let user = { name: "Ashik", age: 25 };
// Creating a new object (immutability)
let updatedUser = { ...user, age: 26 };
console.log(user); // { name: "Ashik", age: 25 } (original unchanged)
console.log(updatedUser); // { name: "Ashik", age: 26 } (new object)
Immutable Array Update
let numbers = [1, 2, 3];
// Creating a new array instead of modifying
let newNumbers = [...numbers, 4];
console.log(numbers); // [1, 2, 3] (unchanged)
console.log(newNumbers); // [1, 2, 3, 4] (new array)
4. Why Use Immutability?
✅ Predictability – Prevents unexpected side effects
✅ Performance Optimization – Helps in React’s state management (React uses immutability in useState)
✅ Debugging Ease – Makes debugging easier as data doesn't change unexpectedly
Top comments (0)