💻 Programming

Immutable

Immutable

An object that cannot be changed after creation. A core concept of functional programming.

📖 Detailed Explanation

Immutable refers to data that cannot be changed at all once it has been created. If you want to modify immutable data, you must create new data instead of changing the existing value. In JavaScript, primitive types such as strings and numbers are immutable by default, and objects and arrays are mutable but can be handled immutably.

Immutability is one of the core principles of functional programming. When data does not change, it becomes easier to track the state of a program, and unexpected side effects can be prevented. In particular, when the same data is referenced from multiple places, maintaining immutability fundamentally prevents bugs in which a change in one place affects another.

Modern front-end libraries such as React and Redux have adopted immutability as a core design principle. React decides whether to re-render by comparing whether the reference of the state has changed, so immutable updates are essential. This makes efficient change detection and performance optimization possible.

In practice, immutability is maintained by using the spread operator (...), Object.assign(), and array methods (map, filter, concat). For complex nested structures, libraries such as Immer and Immutable.js help write immutable updates more intuitively.

💻 Code Example

// 1. 원시 타입은 기본적으로 불변
let str = "Hello";
str[0] = "h";  // 작동하지 않음
console.log(str); // "Hello" (변경되지 않음)

// 2. 객체의 불변적 업데이트 (스프레드 연산자)
const user = { name: "김철수", age: 25, city: "서울" };

// ❌ 잘못된 방법: 직접 수정 (mutable)
// user.age = 26;

// ✅ 올바른 방법: 새 객체 생성 (immutable)
const updatedUser = { ...user, age: 26 };
console.log(user.age);        // 25 (원본 유지)
console.log(updatedUser.age); // 26 (새 객체)

// 3. 배열의 불변적 업데이트
const numbers = [1, 2, 3, 4, 5];

// ❌ 잘못된 방법: push, splice 등은 원본을 변경
// numbers.push(6);

// ✅ 올바른 방법: 새 배열 생성
const added = [...numbers, 6];           // [1, 2, 3, 4, 5, 6]
const removed = numbers.filter(n => n !== 3); // [1, 2, 4, 5]
const doubled = numbers.map(n => n * 2);      // [2, 4, 6, 8, 10]

// 4. 중첩 객체의 불변적 업데이트
const state = {
    user: { name: "박영희", profile: { email: "yh@email.com" } },
    posts: [{ id: 1, title: "첫 글" }]
};

// 깊은 중첩 구조 업데이트 (번거롭지만 불변)
const newState = {
    ...state,
    user: {
        ...state.user,
        profile: { ...state.user.profile, email: "new@email.com" }
    }
};

// 5. Immer 라이브러리로 간단하게 (produce 함수)
// import { produce } from 'immer';
// const newState = produce(state, draft => {
//     draft.user.profile.email = "new@email.com"; // 마치 직접 수정하는 것처럼
// });

🗣️ Say It Like This in Practice

💬 In a Meeting
"When updating Redux state, you must maintain immutability. If you modify state directly, re-rendering won't happen, so it's easier to create a new object with the spread operator and return it, or to use Immer."
💬 In an Interview
"The reason immutability matters in React is that it detects changes through shallow comparison. If you modify an object directly, the reference stays the same, so React does not recognize the change; you have to create a new object to trigger a re-render."
💬 In a code review
"You used push on the array here, but this changes the original array. For immutability, please change it to the form `[...array, newItem]` using the spread operator. It will make tracking state much easier when debugging later."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
The Shallow Copy Pitfall

The spread operator copies only one level. Nested objects still share the same reference, so when modifying a deeply nested structure, you must create new objects at every level.

❌
Confusing Array Methods

push, pop, splice, sort, and reverse are mutable methods that change the original. map, filter, concat, slice, toSorted, and toReversed are immutable approaches that return a new array.

✅
Structural Sharing for Performance

Immutability does not mean copying everything every time. Libraries such as Immutable.js use structural sharing to create only the changed parts anew, optimizing memory and performance.

🔗 Related Terms

📚 Learn More