Sknoe / Notes

JavaScript Immutability: Change the Data Without Breaking the Original

Ever update one object and see another part of your app change too? Learn how JavaScript immutability helps you make safe, predictable updates.

4 min read

Ever update one product and see another part of your app change too? It can happen even if that other part never touched the product. Wait, how can changing one value affect something else?

Sometimes both parts of your code are looking at the same object. Change the object through one name, and the change is visible through the other name too. Once you see that, a useful JavaScript idea makes a lot more sense: instead of changing the old data, make a new version with the change you want.

That habit is called immutability. The word sounds serious, but the idea is friendly: keep the original value as it was, and create an updated copy. Come see why this makes JavaScript—and especially React state—easier to reason about.

How can changing one object affect another?

javascript
const product = { id: 'sku-101', name: 'Trail Backpack', price: 64 };
const selectedProduct = product;
selectedProduct.price = 59;
console.log(product.price); // 59

We gave the same object two names: product and selectedProduct. We did not make a second product. Both names point to the same object, so changing selectedProduct.price is also visible when we read product.price.

Mutation is allowed in JavaScript, but it can surprise us when another part of the code still uses that same value.

Does const stop an object from changing?

No—and this catches a lot of people at first. const stops you from assigning a different value to the variable. It does not freeze the object or array that the variable refers to.

javascript
const product = { name: 'Trail Backpack', price: 64 };
product.price = 59; // Allowed: the object was changed
// product = { name: 'Rain Shell', price: 89 }; // Error: reassigning a const

So const protects the variable binding, not every property inside the object. If we want an updated object without changing the existing one, we can create a copy with object spread:

javascript
const product = { name: 'Trail Backpack', price: 64 };
const saleProduct = { ...product, price: 59 };
console.log(product.price); // 64
console.log(saleProduct.price); // 59

The spread syntax (...) copies the product's properties into a new object. Then price: 59 sets the new object's price. The old object stays as it was. The spread version comes first, so the new price wins.

How do I update an array without changing the original?

Arrays can be mutated too. push() adds to the existing array:

javascript
const products = ['Backpack', 'Rain Shell'];
products.push('Trail Shoes');

To keep the original array unchanged, create a new array with the old items and the new item:

javascript
const products = ['Backpack', 'Rain Shell'];
const nextProducts = [...products, 'Trail Shoes'];

products still contains two items; nextProducts contains three. The three dots spread the existing items into a new array.

The same idea works when removing or updating items. filter() returns an array containing the items that pass a test. map() returns a new array with a result for each item:

javascript
const products = [
{ id: 'sku-101', name: 'Backpack', inStock: true },
{ id: 'sku-102', name: 'Rain Shell', inStock: true },
];
const withoutBackpack = products.filter((item) => item.id !== 'sku-101');
const markedSoldOut = products.map((item) =>
item.id === 'sku-101' ? { ...item, inStock: false } : item
);

withoutBackpack is a new array without the backpack. markedSoldOut is another new array; for the matching product, it also creates a new object with inStock set to false. The original array and its product objects remain unchanged. You do not need to memorize every array method yet; tomorrow’s guide will take those one at a time.

Why does this matter in React?

React state is data a component remembers between renders. React’s guidance is to treat objects and arrays in state as read-only: make a new value when updating, then pass that value to the state setter.

jsx
function markSoldOut(id) {
setProducts((currentProducts) =>
currentProducts.map((product) =>
product.id === id ? { ...product, inStock: false } : product
)
);
}

The state-setter callback receives the current product list. map() makes a new array; object spread makes a new object for the product being changed. That gives React a new value to render, while the previous state remains untouched.

One small thing to remember about spread

javascript
const product = {
name: 'Trail Backpack',
details: { color: 'green', size: 'large' },
};
const greenProduct = {
...product,
details: { ...product.details, color: 'blue' },
};

We copied both the outer product and its nested details object, so changing the color in greenProduct does not change product.details.color. Copy each level you change; spread is not a deep-cloning tool.

Want to see what the array methods are doing?

That’s the next step. In JavaScript Before React, we unpacked map(), filter(), and callbacks before bringing them into React-looking code. Next, we’ll slow down and compare map(), filter(), find(), and reduce()—what each one returns, and when to reach for it.

Did this click?

Tap the bulb if this explanation helped.

Further reading

Updating Arrays in State — React

Updating Objects in State — React

Immutable — MDN Web Docs

JavaScript Destructuring and Spread: React and API Examples