Sub topic 4
Copying Objects and Arrays with Spread
This chapter assumes you know how references work (covered earlier) and that you are comfortable with object and array literals. The goal here is to change data by building a new value instead of editing the old one, using spread syntax and Object.assign.
The spread operator for objects
Object spread (...) copies an object's own enumerable properties into a new object literal. Properties written after the spread override the copied ones, so one expression can copy an object and change it.
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 was createdOrder matters. If you write { name: 'Grace', ...user }, the spread runs last and puts 'Ada' back. Put defaults first and overrides last:
const defaults = { theme: 'light', fontSize: 14 };
const prefs = { theme: 'dark' };
const settings = { ...defaults, ...prefs };
console.log(settings); // { theme: 'dark', fontSize: 14 }Object.assign
Object.assign(target, ...sources) copies properties from the sources into the target and returns the target. It mutates its first argument. To copy without mutating, pass an empty object as the target:
const base = { a: 1 };
const merged = Object.assign({}, base, { b: 2 });
console.log(base); // { a: 1 }
console.log(merged); // { a: 1, b: 2 }The two tools differ in a few ways:
| Aspect | Spread `{ ...obj }` | `Object.assign(target, obj)` |
|---|---|---|
| Creates a new object | Always | Only if `target` is a new object |
| Triggers setters on target | No (defines properties) | Yes (assigns properties) |
| Typical use | Immutable updates | Merging into an existing object |
For immutable code, spread is the usual choice because it cannot mutate by accident.
Spread for arrays
Array spread copies the elements into a new array. You can add items at either end in the same expression:
const nums = [2, 3];
const withEnds = [1, ...nums, 4];
console.log(nums); // [2, 3]
console.log(withEnds); // [1, 2, 3, 4]Shallow means one level deep
Spread and Object.assign copy only the top level. Nested objects and arrays are copied as references, so the copy and the original share them.
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 sharedThe fix in the callout is the basic pattern for nested updates: copy each level you change. A later chapter builds on this for deeper structures.
Common errors
- Assuming spread is a deep copy. It is not. Check whether you mutate anything below the top level.
- Wrong override order.
{ ...changes, ...original }throws away your changes. - Using
Object.assign(obj, changes). This editsobjin place. Pass{}as the first argument instead. - Spreading
nullinto an array.{ ...null }is fine and gives{}, but[...null]throws aTypeErrorbecausenullis not iterable.
Exercise
Given const cart = { owner: 'Ada', items: ['pen'] };, write one expression that returns a new cart with 'ink' appended to items, leaving cart.items unchanged.
Show answer
const next = { ...cart, items: [...cart.items, 'ink'] }; The outer spread copies the top level, and the inner array spread creates a new items array, so cart.items stays ['pen'].
Exercise
What does console.log({ ...{ a: 1, b: 2 }, ...{ b: 3 }, a: 0 }) print, and why?
Show answer
{ a: 0, b: 3 }. Properties are applied left to right, so b: 3 overrides b: 2, and the literal a: 0 written last overrides a: 1.