Skip to main content
Practice Problems

Immutability and mutability in JavaScript

In JavaScript data can be changed in two ways: mutably and immutably. Understanding difference between them is especially important when working with state in React, Redux and other libraries.


Mutability

Mutability means object can be changed after creation.

js
const user = { name: "Alice" }; user.name = "Bob"; // change directly console.log(user); // { name: "Bob" }

Such changes happen by reference and can cause unpredictable behavior, especially if same object is used in multiple places

Immutability

Immutability means object doesn't change, and when changes occur new copy is created.

js
const user = { name: "Alice" }; const updatedUser = { ...user, name: "Bob" }; // create new object console.log(user); // { name: "Alice" } console.log(updatedUser); // { name: "Bob" }

Immutability makes data predictable and safe for comparison, which is critical when re-rendering components in React.

Immutability in React

React doesn't track changes by object content, it compares them by reference (===).

Therefore mutable update won't trigger re-render:

jsx
// wrong approach state.items.push("newItem"); setState(state); // same reference → React won't update component

Correct immutable way:

jsx
// create new array setState({ ...state, items: [...state.items, "newItem"] });

Comparison

PropertyMutabilityImmutability
Data changeMade directly in objectNew copy is created
Behavior in ReactMay not trigger re-renderAlways reliably triggers re-render
Data safetySide effects possibleData protected from mutations
Debugging convenienceHarder to trackEasier to track changes

Immutable Operation Examples:

js
// arrays const newArr = [...oldArr, newItem]; const filtered = oldArr.filter(item => item !== target); // objects const newObj = { ...oldObj, updatedKey: newValue }; // nested objects const updated = { ...state, user: { ...state.user, name: "John", }, };

Conclusion:

Use immutability to make code predictable, safe and compatible with React. This is foundation of correct work of useEffect, React.memo, Redux and other tools.

Content

MutabilityImmutabilityImmutability in ReactComparisonImmutable Operation Examples:

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems