Back to all questions

What is immutability?

Devs Hive

Devs Hive

Seen on interview: 2 users

Immutability is a programming approach in which data is not changed after it is created. Instead of modifying existing data structures, a new copy with the updated values is created.

This way, we avoid unexpected updates to variables or objects. This technique is especially useful when the code is complex and tangled. Immutable code is much easier to test and is generally more predictable.

A simple usage example

// В середині forEach ми мутуємо вихідні дані
// Якщо таких мутацій буде декілька або функція буде велика, ми можемо загубитись в коді.
// Це призведе до неочікуваних багів, які буде складно пофіксити
const users = [
{ name: "Alex", age: 30 },
{ name: "John", age: 25 }
];

users.forEach((user) => {
user.age += 1; // змінює об'єкт всередині існуючого масиву
});

// --------------------------------------------------------------------------------

// Краще буде використати .map, який створить копію масиву, де і будуть зміни.
// Ми не змінюємо вихідний масив, що робить наш код більш передбачуваним і простим
const users = [
{ name: "Alex", age: 30 },
{ name: "John", age: 25 }
];

const updatedUsers = users.map((user) => {
return {
...user,
age: user.age + 1, // створюємо новий об'єкт замість зміни існуючого
};
});

This technique is widely used in the JS world, especially on the frontend, for example in most libraries and frameworks. Also, JS itself is getting immutable alternatives to existing methods. For example toSorted, toReversed, with, toSpliced, etc.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!