Sub topic 8
Spreading Objects to Copy and Merge
This chapter assumes you know how to declare variables with let and const, how to work with plain objects, and how array spread works from the previous chapter. You should also know the difference between primitive values and references.
Object spread uses the same ... token you saw in array literals, placed inside an object literal. It copies properties from one object into the new object you are building. It is the standard way to make a quick copy, merge several objects, or build an object with some properties changed.
The Basic Syntax
Write ... followed by any expression inside { }. The engine reads the expression's own enumerable properties and defines each one on the new object.
const point = { x: 1, y: 2 };
const copy = { ...point };
console.log(copy); // { x: 1, y: 2 }
console.log(copy === point); // false (a new object)
const point3d = { ...point, z: 3 };
console.log(point3d); // { x: 1, y: 2, z: 3 }copy is a different object with the same properties. Changing copy.x does not change point.x, because x holds a primitive. Nested objects behave differently, and the chapter "Spread Copies Are Shallow" covers that case.
Merging and Override Order
You can spread several objects into one literal and mix them with ordinary properties. The literal is evaluated left to right. When two sources have the same key, the one that comes later wins.
const defaults = { theme: 'light', fontSize: 14, lang: 'en' };
const userPrefs = { theme: 'dark', fontSize: 16 };
const settings = { ...defaults, ...userPrefs, lang: 'fr' };
console.log(settings); // { theme: 'dark', fontSize: 16, lang: 'fr' }Order matters, and it is easy to get it backwards. Put the general values first and the specific ones last.
const userPrefs = { theme: 'dark' };
const wrong = { theme: 'light', ...userPrefs }; // the user's value wins
const forced = { ...userPrefs, theme: 'light' }; // 'light' always wins
console.log(wrong.theme); // 'dark'
console.log(forced.theme); // 'light'The first form reads "use light unless the user said otherwise." The second form reads "the user can't change the theme." Both are valid, but they mean opposite things.
Key Order After an Override
An overwritten key keeps the position it got when it was first added. It does not move to the end.
const result = { ...{ a: 1, b: 2 }, a: 3 };
console.log(Object.keys(result)); // ['a', 'b']
console.log(result); // { a: 3, b: 2 }This matters if you serialize objects with JSON.stringify and compare the strings, or display keys in order. The usual property order rules also apply: integer-like keys such as '1' come first in ascending order, then string keys in insertion order, then symbols.
What Gets Copied
Object spread copies only own enumerable properties. An own property is defined directly on the object, not inherited through the prototype chain. An enumerable property is one that shows up in Object.keys and for...in. The table summarizes what happens to each kind of property.
| Property kind | Copied by spread? | Notes |
|---|---|---|
| Own enumerable string keys | Yes | The common case |
| Own enumerable symbol keys | Yes | Unlike `JSON.stringify`, symbols survive |
| Non-enumerable properties | No | Skipped silently |
| Inherited properties (prototype) | No | Includes class methods |
| Getters | Value only | The getter runs once and its result is copied as a plain data property |
| Setters on the new object | Not triggered | Spread defines properties, it does not assign them |
Symbols and Non-Enumerable Properties
const id = Symbol('id');
const source = { name: 'Ada', [id]: 42 };
Object.defineProperty(source, 'secret', { value: 'hidden', enumerable: false });
const copy = { ...source };
console.log(copy[id]); // 42
console.log(copy.secret); // undefined
console.log('secret' in copy); // falseGetters Become Plain Values
Spread reads each property, so a getter runs once at copy time. The copy stores the result as an ordinary data property and keeps no link to the original getter.
let calls = 0;
const live = {
get stamp() {
calls += 1;
return calls;
}
};
const snapshot = { ...live };
console.log(calls); // 1 (the getter ran during the spread)
console.log(snapshot.stamp); // 1
console.log(snapshot.stamp); // 1 (still 1; it is a plain value now)
console.log(Object.getOwnPropertyDescriptor(snapshot, 'stamp'));
// { value: 1, writable: true, enumerable: true, configurable: true }The copy also loses attributes. A property that was read-only (writable: false) on the source becomes writable on the copy, because spread creates fresh, fully writable data properties.
Class Instances Lose Their Prototype
Methods defined in a class body live on the prototype, so spread does not copy them. The result is a plain object, not an instance of the class.
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 q = { ...p };
console.log(q); // { x: 3, y: 4 }
console.log(q instanceof Point); // false
console.log(typeof q.length); // 'undefined'If you need an updated instance of a class, write a method that returns new Point(...). You can also use Object.assign(Object.create(Object.getPrototypeOf(p)), p), but that copies the properties and still skips anything private or non-enumerable.
Spreading Non-Objects
Object spread is lenient about what you give it. It converts the value to an object where it can and copies that object's own enumerable properties.
console.log({ ...null }); // {}
console.log({ ...undefined }); // {}
console.log({ ...42 }); // {}
console.log({ ...true }); // {}
console.log({ ...'hi' }); // { '0': 'h', '1': 'i' }
console.log({ ...['a', 'b'] }); // { '0': 'a', '1': 'b' }Two points follow from this:
- Spreading
nullorundefinedinto an object literal does not throw. Array spread,[...null], does throw aTypeError, because it needs an iterable. Destructuringnullalso throws, as the chapter on pitfalls explains. - Strings and arrays become objects with index keys. That is rarely what you want. If you see numeric keys in a merged object, look for an array or string that got spread by accident.
Conditional Properties
Because spreading false, null, or undefined adds nothing, you can include properties only when a condition holds.
function buildQuery(term, page, includeArchived) {
return {
q: term,
...(page > 1 && { page }),
...(includeArchived ? { archived: true } : {}),
};
}
console.log(buildQuery('cats', 1, false)); // { q: 'cats' }
console.log(buildQuery('cats', 3, true)); // { q: 'cats', page: 3, archived: true }The && form is short, but it spreads whatever the left side is when the condition is falsy. For 0 or '' that is harmless, since both spread to nothing. The ternary form with {} says plainly what happens in both cases, and many teams prefer it for that reason.
Spread Defines Properties, It Does Not Assign
When spread puts a property on the new object, it defines it. It does not assign it with =. That difference rarely shows in plain object literals, because the new object has no setters of its own. It does matter when you compare spread with Object.assign, which assigns to an existing target and so does trigger setters. The chapter "Object Spread vs Object.assign" covers that comparison. For now, remember that object spread always builds a new object and never changes any of its sources.
Common Errors
- Reversed merge order. Writing
{ ...overrides, ...defaults }silently throws away the overrides. Specific values go last. - Expecting a deep copy.
{ ...state }copies one level. A nestedstate.userobject is shared between the original and the copy. - Spreading an array into an object.
{ ...list }gives index keys. You probably meant[...list]. - Spreading class instances or built-ins. Methods and internal data are lost.
- Assuming read-only properties stay read-only. Copies are always writable, enumerable, and configurable.
Exercise
What does this code print, and why? const base = { a: 1, b: 2 }; const out = { b: 0, ...base, a: 9 }; console.log(Object.keys(out), out);
Show answer
It prints ['b', 'a'] and { b: 2, a: 9 }. The key b is defined first with 0, then the spread of base adds a (1) and overwrites b with 2, keeping b in first position. Finally a: 9 overwrites a, which keeps its second position.
Exercise
A teammate writes const copy = { ...new Set([1, 2, 3]) } and const merged = { ...null, x: 1 }. What are copy and merged, and does either line throw?
Show answer
Neither line throws. copy is {} because a Set keeps its values in internal slots, not in own enumerable properties. merged is { x: 1 } because spreading null into an object literal adds nothing. In contrast, [...null] would throw a TypeError.
Exercise
Write a function withTimeout(options) that returns a new object containing all of options, with timeout set to 5000 only when options does not already supply a timeout. It must not modify options.
Show answer
function withTimeout(options) { return { timeout: 5000, ...options }; } Putting the default first lets any timeout in options override it, and the spread builds a new object, so options is unchanged. (If options.timeout exists but is undefined, the result's timeout is undefined. Use options.timeout ?? 5000 after the spread if you want to treat undefined as missing.)