What is Immutability?
JavaScript
Immutability
An immutable value is one whose content cannot be changed without creating an entirely new value.
In JavaScript, primitive values are immutable, once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned another value. By contrast, objects and arrays are mutable by default, their properties and elements can be changed without reassigning a new value.
Modifying an array
JAVASCRIPT
1// Mutable approach (modifying original array)2const numbers = [1, 2, 3];3numbers.push(4); // Directly modifies original array4console.log(numbers); // [1, 2, 3, 4]56// Immutable approach7const originalNumbers = [1, 2, 3];8const newNumbers = [...originalNumbers, 4]; // Creates new array9console.log(originalNumbers); // [1, 2, 3]10console.log(newNumbers); // [1, 2, 3, 4]
Modifying an object
JAVASCRIPT
1// Mutable approach2const user = { name: 'John', age: 30 };3user.age = 31; // Modifies original object45// Immutable approach6const originalUser = { name: 'John', age: 30 };7const updatedUser = { ...originalUser, age: 31 }; // Creates new object
Resources
You can read more about immutability on Immutable - MDN.