← Tous les articles

JavaScript: copy an object or array without changing the original (spread, structuredClone and the traps)

You change a copy and the original changes too? References, shallow and deep copies explained with examples: spread, Object.assign, structuredClone, the limits of JSON.parse(JSON.stringify()) and the array methods that don't mutate in place.

JavaScript: copy an object or array without changing the original (spread, structuredClone and the traps)

Key points

  • Assigning an object to a variable in JavaScript doesn’t copy it: both variables point to the same object.
  • Spread (…) and Object.assign only copy the top level; structuredClone makes a true deep copy, including Date and Map.
  • When updating state (React, Vue, stores), copy only the path you change, and prefer toSorted() or with() over methods that mutate arrays in place.

It’s one of the most common JavaScript bugs, and one of the most confusing: you make a copy of an object so you can edit it, and the original changes as well. An edit form that alters the data before the user clicks “Save”, a basket whose quantities change on their own, a component that doesn’t re-render even though the data changed. Behind all of these there’s almost always the same cause: the difference between a reference, a shallow copy and a deep copy. Here’s how it works, and which tool to reach for in each case.

Why your copy changes the original

Primitive values (numbers, strings, booleans) are copied when you assign them. Objects and arrays aren’t: a variable holds a reference to the object. Writing const copy = cart puts a second label on the same object; it doesn’t create a new one.

const cart = { customer: 'A12', lines: [{ sku: 'TS-01', qty: 1 }] };

const copy = cart;             // not a copy: a second label for the same object
copy.customer = 'B07';
console.log(cart.customer);    // 'B07': the original changed

const copy2 = { ...cart };     // shallow copy
copy2.customer = 'C33';        // fine, cart.customer is untouched
copy2.lines[0].qty = 5;        // trap: lines is shared
console.log(cart.lines[0].qty); // 5

The second half of the example shows the most common trap. The spread syntax { ...cart } does create a new object, but it copies properties as they are: if a property holds an array or object, it’s the reference that gets copied. The top level is independent; everything below it is shared. That’s a shallow copy.

Object.assign({}, cart), Array.from(), [...array] and array.slice() behave exactly the same way. They’re fine for a “flat” object whose values are all primitives, which covers a lot of cases. As soon as there’s nesting, you need to think.

On our projects this bug shows up most often in edit forms: you load a record from the API, write const draft = { ...record } so the user can cancel, then they edit a nested address and cancelling restores nothing, because the draft’s address and the record’s address are the same object.

Deep copies with structuredClone()

To get a copy that’s fully independent at every level, the modern answer is structuredClone(). It’s a built-in function, available in all current browsers and in Node.js since version 17. It walks the whole object and recreates every level.

const quote = {
  createdAt: new Date('2026-11-19T09:30:00Z'),
  options: new Map([['shipping', 'express']]),
  lines: [{ sku: 'TS-01', qty: 1 }],
};

const clone = structuredClone(quote);
clone.lines[0].qty = 3;
console.log(quote.lines[0].qty);             // 1: the original is intact
console.log(clone.createdAt instanceof Date); // true
console.log(clone.options.get('shipping'));   // 'express'

// What JSON does to the same object
const viaJson = JSON.parse(JSON.stringify(quote));
console.log(typeof viaJson.createdAt); // 'string': the date became text
console.log(viaJson.options);          // {}: the Map is gone

Comparing it with JSON.parse(JSON.stringify()), the old trick, is revealing. Going through JSON:

  • turns dates into strings;
  • loses Map, Set, regular expressions and any other type JSON doesn’t have;
  • drops properties whose value is undefined;
  • converts NaN and Infinity to null;
  • throws on an object that references itself, whereas structuredClone handles circular references.

In other words, the JSON trick works as long as your data already looks like JSON (an API response, say), and produces silent bugs otherwise. We replace it with structuredClone as a matter of course in code we take over.

What structuredClone can’t do

structuredClone uses the structured clone algorithm, the same one used to pass data to a Web Worker or store it in IndexedDB. It copies data, not behaviour. Three limits to know:

class LineItem {
  constructor(sku, price) { this.sku = sku; this.price = price; }
  total(qty) { return this.price * qty; }
}

const item = new LineItem('TS-01', 19.9);
const c = structuredClone(item);
console.log(c instanceof LineItem); // false: it's a plain object
// c.total(2) -> TypeError: c.total is not a function

structuredClone({ onSave() {} }); // DataCloneError: functions can't be cloned

// For a class, write a dedicated method
LineItem.prototype.clone = function () { return new LineItem(this.sku, this.price); };
  • Functions can’t be cloned: an object holding a method or callback throws a DataCloneError.
  • Class instances lose their prototype: you get a plain object with the same properties but none of the methods. For your own classes, an explicit clone() method is still the clearest option.
  • DOM elements can’t be cloned with structuredClone; use element.cloneNode(true) for those.

Getters and setters are evaluated at copy time too: the clone holds their value, not their logic. In practice, if your object is “state” or serialisable business data, structuredClone does the job. If it’s an object with behaviour, copy it with a method written for it.

Performance-wise, a deep copy walks the entire object. Copy a state of several thousand items on every keystroke and you’ll feel it. That’s one reason UI libraries favour a different approach, described next.

Updating state without mutating it (React, Vue, stores)

In React, and in many state managers, the rule is never to modify state in place: you hand over a new object, and the library compares references to work out what changed. Mutate a nested array directly and the state’s reference doesn’t change, so the screen doesn’t update. That’s the classic “I changed the data but nothing happens”.

Deep-copying the whole state on every change would be correct but expensive, and would make the library think everything changed. Best practice is to copy only the path leading to the changed value and reuse the rest:

// Change one line's quantity without touching the original state
function setQuantity(cart, sku, qty) {
  return {
    ...cart,
    lines: cart.lines.map((l) => (l.sku === sku ? { ...l, qty } : l)),
  };
}

// Arrays: in-place methods and their copying counterparts
const prices = [30, 10, 20];
const sorted = prices.toSorted((a, b) => a - b); // prices stays [30, 10, 20]
const reversed = prices.toReversed();
const replaced = prices.with(1, 15);             // [30, 15, 20]
// For older browsers: [...prices].sort((a, b) => a - b)

The returned cart is a new object, its lines array is a new array, the edited line is a new object, and every other line is reused as is. It’s fast, and components showing unchanged lines don’t have to re-render.

Watch out for array methods that mutate in place: sort(), reverse(), splice(), push(). A state.products.sort() inside a render function sorts the state itself. toSorted(), toReversed(), toSpliced() and with(), added to the language in 2023, return a new array; they’re available in recent browsers, and [...array].sort() remains the universal equivalent.

When nested updates get tedious to write, a library such as Immer lets you write code that looks like it mutates the object while producing a correct copy. For deeply nested state it’s often more readable; on a small project, spread is enough.

Finally, Object.freeze() can help catch accidental mutations during development, but it’s shallow too: it only freezes the top level.

FAQ

What’s the difference between a shallow and a deep copy?

A shallow copy creates a new object but shares nested objects and arrays with the original. A deep copy recreates every level, so changing the copy never affects the original.

Should I still use JSON.parse(JSON.stringify())?

Only for data that’s already plain JSON. Otherwise structuredClone is safer: it keeps dates, Maps and Sets, and handles circular references.

Why isn’t my React component updating?

Very often because state was mutated in place (push, sort, assigning to a nested object): the reference didn’t change, so React sees no difference. Return a new object by copying the path you changed.

Is your JavaScript app piling up hard-to-reproduce state bugs? We audit and take over existing front ends, and build solid, maintainable web applications.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →