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

// Mutable approach (modifying original array)
const numbers = [1, 2, 3];
numbers.push(4); // Directly modifies original array
console.log(numbers); // [1, 2, 3, 4]

// Immutable approach
const originalNumbers = [1, 2, 3];
const newNumbers = [...originalNumbers, 4]; // Creates new array
console.log(originalNumbers); // [1, 2, 3]
console.log(newNumbers); // [1, 2, 3, 4]

Modifying an object

// Mutable approach
const user = { name: 'John', age: 30 };
user.age = 31; // Modifies original object

// Immutable approach
const originalUser = { name: 'John', age: 30 };
const updatedUser = { ...originalUser, age: 31 }; // Creates new object

Resources

You can read more about immutability on Immutable - MDN.

00:00