Curriculum Series

What is Immutability?

What is Immutability?

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 array
4console.log(numbers); // [1, 2, 3, 4]
5
6// Immutable approach
7const originalNumbers = [1, 2, 3];
8const newNumbers = [...originalNumbers, 4]; // Creates new array
9console.log(originalNumbers); // [1, 2, 3]
10console.log(newNumbers); // [1, 2, 3, 4]

Modifying an object

JAVASCRIPT
1// Mutable approach
2const user = { name: 'John', age: 30 };
3user.age = 31; // Modifies original object
4
5// Immutable approach
6const originalUser = { name: 'John', age: 30 };
7const updatedUser = { ...originalUser, age: 31 }; // Creates new object

Resources

You can read more about immutability on Immutable - MDN.

Finished reading?

Mark this topic as solved to track your progress.