Sub topic 4
Copying Objects and Arrays with Spread
This chapter assumes you know JavaScript objects and arrays and understand that object variables hold references. It also builds on the earlier point that const does not freeze a value. Here you will learn the most common tool for updating data without mutation: making a new object or array that starts as a copy of the old one, with your changes applied.
The Core Idea: Copy, Then Change the Copy
Mutating an object changes it in place, and everyone holding a reference to it sees the change. The immutable alternative is to build a new value. The old value stays as it was, and anyone who needs the new state reads the new reference.
Spread syntax (...) is the shortest way to do this. Inside an object literal, ...source copies the source's own enumerable properties into the new object. Inside an array literal, ...source iterates the source and puts each element into the new array.
const user = { name: 'Ada', role: 'admin' };
const renamed = { ...user, name: 'Grace' };
console.log(user.name); // 'Ada'
console.log(renamed.name); // 'Grace'
console.log(renamed === user); // false, a new object
const nums = [1, 2, 3];
const more = [...nums, 4];
console.log(nums); // [1, 2, 3]
console.log(more); // [1, 2, 3, 4]Object Spread in Detail
Later Properties Win
An object literal is evaluated left to right. If a key appears twice, the last value wins. This rule is what makes the "copy, then override" pattern work.
const defaults = { theme: 'light', fontSize: 14, beta: false };
const prefs = { theme: 'dark' };
const settings = { ...defaults, ...prefs };
console.log(settings); // { theme: 'dark', fontSize: 14, beta: false }
const wrongOrder = { ...prefs, ...defaults };
console.log(wrongOrder.theme); // 'light', defaults overwrote the preferenceA frequent bug is putting the override before the spread, as in { name: 'Grace', ...user }. The spread then copies user.name over your new value, and the update quietly does nothing.
Adding, Overriding, and Removing Keys
Spread handles adding and overriding directly. To remove a key without mutation, use rest destructuring. It collects every property you did not name into a new object.
const account = { id: 7, email: '[email protected]', password: 'hunter2' };
const withVerified = { ...account, verified: true }; // add
const withNewEmail = { ...account, email: '[email protected]' }; // override
const { password, ...publicAccount } = account; // remove
console.log(publicAccount); // { id: 7, email: '[email protected]' }
console.log(account.password); // 'hunter2', the original is untouchedUse this instead of delete, which mutates the original object.
Computed Keys and Conditional Properties
When the key comes from a variable, use a computed key. To include a property only under some condition, spread a value that may be falsy. Spreading false, null, or undefined inside an object literal adds nothing and does not throw.
function setField(form, field, value) {
return { ...form, [field]: value };
}
const form = setField({ name: '', age: '' }, 'age', '36');
console.log(form); // { name: '', age: '36' }
const isAdmin = false;
const request = {
url: '/reports',
...(isAdmin && { includeDrafts: true })
};
console.log(request); // { url: '/reports' }Spread Is Shallow
Spread copies one level deep. The new object gets new slots for its top-level keys, but if a value is an object or an array, the slot holds the same reference as the original. The two objects then share that nested value.
const original = { name: 'Ada', tags: ['math'] };
const copy = { ...original, name: 'Grace' };
console.log(original.name); // 'Ada'
copy.tags.push('code');
console.log(original.tags); // ['math', 'code'] because the nested array is shared
console.log(copy.tags === original.tags); // trueA shallow copy is safe only as long as you never mutate the shared nested values through either object. If you need to change a nested value, copy that level too, for example { ...original, tags: [...original.tags, 'code'] }. The chapter on nested updates turns this into a general technique.
What Object Spread Copies and What It Drops
Object spread copies own, enumerable properties, including symbol-keyed ones. Everything else is left out. This matters as soon as you spread anything other than a plain object.
| Source feature | Copied by `{ ...obj }`? | Result in the copy |
|---|---|---|
| Own enumerable string keys | Yes | Same values |
| Own enumerable symbol keys | Yes | Same values |
| Non-enumerable properties | No | Missing |
| Inherited properties and prototype | No | Copy's prototype is `Object.prototype` |
| Getters | Value only | Getter is called once and becomes a plain data property |
| Setters | No | Missing, or plain data if paired with a getter |
| Internal slots (Date, Map, Set) | No | Usually an empty object `{}` |
The prototype is the item that causes the most bugs. Spreading a class instance gives you a plain object without the class's methods.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const p = new Point(3, 4);
const moved = { ...p, x: 6 };
console.log(moved.x); // 6
console.log(moved instanceof Point); // false
console.log(typeof moved.length); // 'undefined', the method lived on the prototype
const date = new Date(0);
console.log({ ...date }); // {}, a Date keeps its time in an internal slot
const map = new Map([['a', 1]]);
console.log({ ...map }); // {}
const mapCopy = new Map(map); // copy a Map through its constructor
console.log(mapCopy.get('a')); // 1For class instances, give the class a method that returns a new instance, such as withX(x) { return new Point(x, this.y); }. For Date, Map, and Set, use their constructors: new Date(d), new Map(m), new Set(s). If you need to keep the prototype of an arbitrary object, Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)) copies the prototype and the property descriptors, getters included. It is still shallow.
Object.assign: The Older Alternative
Before object spread arrived in ES2018, people wrote Object.assign({}, source). It copies own enumerable properties from each source into the target, left to right, and returns the target.
const base = { a: 1, b: 2 };
const viaAssign = Object.assign({}, base, { b: 3 });
const viaSpread = { ...base, b: 3 };
console.log(viaAssign); // { a: 1, b: 3 }
console.log(viaSpread); // { a: 1, b: 3 }For plain objects the results match, but the two differ in ways that matter:
- The target is mutated.
Object.assign(state, changes)changesstatein place. That mutation is exactly what you are trying to avoid. An empty{}as the first argument is what makes the call immutable. - Setters run.
Object.assignwrites with ordinary assignment, so a setter on the target fires. Spread defines new properties on a fresh object and never calls setters. - Dynamic source lists.
Object.assign({}, ...arrayOfObjects)merges a list of objects whose length you don't know in advance. You can write the same thing witharrayOfObjects.reduce((acc, o) => ({ ...acc, ...o }), {}), but that version builds a new object on every step.
const target = {
set value(v) { console.log('setter ran with', v); }
};
Object.assign(target, { value: 1 }); // logs: setter ran with 1
const spreadCopy = { ...target, value: 2 }; // logs nothing
console.log(spreadCopy.value); // 2Prefer spread in new code. Use Object.assign with an empty target when you have an array of sources to merge.
Array Spread in Detail
Array spread works on any iterable, meaning anything that provides Symbol.iterator. That includes arrays, strings, Set, Map, arguments, and NodeList. It is useful for converting these to arrays, and also for copying arrays.
const letters = [...'hey']; // ['h', 'e', 'y']
const unique = [...new Set([1, 1, 2, 3])]; // [1, 2, 3]
const entries = [...new Map([['a', 1]])]; // [['a', 1]]
const a = [1, 2];
const b = [3, 4];
const combined = [...a, 0, ...b]; // [1, 2, 0, 3, 4]
const prepended = [0, ...a]; // [0, 1, 2]Array copies are shallow in the same way object copies are. [...todos] gives you a new array, but every element is the same object as before. Mutating copy[0].done changes todos[0].done too.
Gotchas Specific to Arrays
Spreading a non-iterable throws. Object spread ignores null and undefined. Array spread does not.
const fromApi = null;
const safeObject = { ...fromApi }; // {}
// const broken = [...fromApi]; // TypeError: fromApi is not iterable
const safeArray = [...(fromApi ?? [])]; // []Holes become undefined. A sparse array has missing indexes. Spread reads each index through the iterator, so the copy gets real undefined entries in their place. slice() keeps the holes. This rarely matters, but it can change the results of forEach and in checks.
const sparse = [1, , 3];
console.log(1 in sparse); // false, index 1 is a hole
console.log(1 in [...sparse]); // true, now it holds undefined
console.log(1 in sparse.slice()); // false, slice preserves the holeSpreading an array into an object gives index keys. { ...['x', 'y'] } produces { 0: 'x', 1: 'y' }, a plain object with no length and no array methods. If you meant to copy the array, use square brackets.
Very large spreads into function calls can fail. Math.max(...hugeArray) passes every element as an argument. Engines limit how many arguments a call can take, so arrays with hundreds of thousands of elements can throw a RangeError. Array literals like [...hugeArray] don't have this limit.
Cost: Spread Is O(n) Per Copy
Each spread copies every top-level property or element, so one copy costs time proportional to its size. That is usually fine. It becomes a problem inside loops, where repeated copying turns linear work into quadratic work.
const items = Array.from({ length: 5 }, (_, i) => ({ id: i, label: `Item ${i}` }));
// Quadratic: each step copies the whole accumulator
const slowIndex = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});
// Linear: build the result once
const fastIndex = Object.fromEntries(items.map(item => [item.id, item]));
console.log(Object.keys(slowIndex).length === Object.keys(fastIndex).length); // trueThe fast version is still immutable from the caller's point of view. It never touches items, and it returns a brand-new object. Mutating a local value that you just created, before anyone else can see it, is safe. Immutability is about values other code already holds.
Common Errors at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| `{ change, ...obj }` | Update is silently undone | Put the spread first: `{ ...obj, change }` |
| Mutating a nested value after a spread | Original changes too | Copy each level you modify |
| `Object.assign(state, changes)` | Original state mutated | `Object.assign({}, state, changes)` or spread |
| Spreading a class instance | Methods missing, `instanceof` false | Return a new instance from a class method |
| `{ ...date }` or `{ ...map }` | Empty object | Use `new Date(d)` or `new Map(m)` |
| `[...maybeNull]` | `TypeError: not iterable` | `[...(maybeNull ?? [])]` |
Exercise
Given const cart = { owner: 'Ada', items: [{ sku: 'A1', qty: 1 }] };, a teammate writes const next = { ...cart }; next.items.push({ sku: 'B2', qty: 2 });. What does cart.items.length print afterwards, and how should the update be written so cart is unchanged?
Show answer
It prints 2. The spread copies only the top level, so next.items and cart.items are the same array, and push mutates it. Write const next = { ...cart, items: [...cart.items, { sku: 'B2', qty: 2 }] };. This makes a new array for items. The existing item objects are still shared, which is fine as long as they are not mutated.
Exercise
What does each expression produce? (a) { ...{ a: 1 }, ...null, a: 2 } (b) [...'ab', ...new Set(['b', 'c'])] (c) { ...['x'] }
Show answer
(a) { a: 2 }. Spreading null in an object literal adds nothing, and the later a: 2 wins. (b) ['a', 'b', 'b', 'c']. Each iterable is expanded in turn, and the Set only removes duplicates inside itself. (c) { 0: 'x' }, a plain object with an index key and no array behavior.
Exercise
Write a function omit(obj, key) that returns a copy of obj without key, without mutating obj and without using delete. The key is only known at runtime.
Show answer
function omit(obj, key) { const { [key]: _removed, ...rest } = obj; return rest; }. Computed-key destructuring pulls out the dynamic key, and the rest pattern collects the remaining own enumerable properties into a new object.