Sub topic 15
Object Spread vs Object.assign
This chapter assumes you already know object spread from the chapter "Spreading Objects to Copy and Merge" and understand from "Spread Copies Are Shallow" that copies share nested objects. You should also know how classes, getters and setters work, and the difference between a property's value and its descriptor.
Before ES2018 added object spread, the standard way to copy or merge objects was Object.assign(target, ...sources). Both tools usually produce the same result, so many developers treat them as interchangeable. They are not interchangeable. The two use different internal operations, and the differences show up with class instances, setters, frozen objects and untrusted input.
What the Two Have in Common
Start with what is the same, so the differences stand out:
- Both copy only own, enumerable properties. Inherited properties and non-enumerable properties are skipped.
- Both copy string keys and symbol keys.
- Both read each source property with an ordinary get. Getters on the source run, and only the value they return is copied.
- Both process sources left to right, so later sources overwrite earlier ones.
- Both make shallow copies. Nested objects are shared between the copy and the source.
- Both skip
nullandundefinedwhen they appear as sources.
const id = Symbol('id');
const proto = { inherited: true };
const source = Object.create(proto);
source.visible = 1;
source[id] = 42;
Object.defineProperty(source, 'hidden', { value: 2, enumerable: false });
const viaSpread = { ...source };
const viaAssign = Object.assign({}, source);
console.log(viaSpread); // { visible: 1, [Symbol(id)]: 42 }
console.log(viaAssign); // { visible: 1, [Symbol(id)]: 42 }
console.log('inherited' in viaSpread, 'hidden' in viaAssign); // false falseDifference 1: Mutation vs a New Object
Object.assign writes into its first argument and returns that same object. Spread always builds a new object literal.
const target = { a: 1 };
const result = Object.assign(target, { b: 2 });
console.log(result === target); // true
console.log(target); // { a: 1, b: 2 } (mutated)
const copy = { ...target, c: 3 };
console.log(copy === target); // false
console.log(target); // { a: 1, b: 2 } (unchanged)The usual non-mutating form is Object.assign({}, a, b). In everyday code it behaves almost the same as { ...a, ...b }. The remaining differences come from how each one writes properties.
Difference 2: Set vs Define
This difference explains most of the others.
Object.assignwrites each property with the internal [[Set]] operation, the same onetarget.key = valueuses. That means setters run, the prototype chain is consulted, and the write fails on read-only properties.- Spread writes each property with CreateDataProperty, the same operation an object literal uses for
{ key: value }. It always creates a plain own data property on the new object, and no setter is ever called.
Setters and class instances
Because Object.assign calls setters, it works with objects whose setters validate or transform values. Spread ignores the class entirely.
class Temperature {
#celsius = 0;
get celsius() { return this.#celsius; }
set celsius(value) {
if (typeof value !== 'number') throw new TypeError('celsius must be a number');
this.#celsius = value;
}
}
const t = new Temperature();
Object.assign(t, { celsius: 21 });
console.log(t.celsius); // 21 (setter ran)
try {
Object.assign(t, { celsius: 'warm' });
} catch (err) {
console.log(err.message); // 'celsius must be a number'
}
console.log({ ...t }); // {} (getter lives on the prototype, private field is not a property)
const plain = { ...t, celsius: 'warm' };
console.log(plain instanceof Temperature); // false
console.log(plain.celsius); // 'warm' (no validation)The spread result has Object.prototype as its prototype. It has no methods, no accessors and no private state. Spread a class instance only when a plain snapshot of its own data is what you want.
Read-only and frozen targets
Object.assign throws a TypeError when it hits a non-writable property, even in non-strict code. Spread writes to a fresh object, so the source's frozen state does not matter, and the copy is not frozen.
const frozen = Object.freeze({ id: 1 });
try {
Object.assign(frozen, { id: 2 });
} catch (err) {
console.log(err instanceof TypeError); // true
}
const updated = { ...frozen, id: 2 };
console.log(updated.id, Object.isFrozen(updated)); // 2 falseThe `__proto__` key and untrusted input
JSON.parse turns a "__proto__" key into an ordinary own property. When Object.assign copies that property, its [[Set]] reaches the __proto__ setter on Object.prototype and replaces the target's prototype. Spread defines a harmless own property named "__proto__" instead.
const payload = JSON.parse('{"__proto__": {"isAdmin": true}}');
const viaSpread = { ...payload };
const viaAssign = Object.assign({}, payload);
console.log(Object.hasOwn(viaSpread, '__proto__')); // true
console.log(viaSpread.isAdmin); // undefined
console.log(viaAssign.isAdmin); // true (inherited from the injected prototype)
console.log(Object.hasOwn(viaAssign, 'isAdmin')); // falseThe global Object.prototype is not polluted here. Only the target's own prototype changes. That is still enough to get past a check like if (config.isAdmin). When you copy data that came from users or the network, prefer spread, or validate the keys first.
Difference 3: Invalid Targets and Primitive Sources
Spread has no target, so it cannot fail because of one. Object.assign requires its first argument to be convertible to an object.
console.log({ ...null, ...undefined }); // {}
console.log(Object.assign({}, null, undefined)); // {}
console.log({ ...'hi' }); // { '0': 'h', '1': 'i' }
console.log({ ...42, ...true }); // {} (number and boolean wrappers have no own enumerable props)
try {
Object.assign(null, { a: 1 });
} catch (err) {
console.log(err instanceof TypeError); // true
}Because { ...maybeNull } never throws, spread is convenient for optional sources such as { ...defaults, ...options }, where options may be missing.
Copying Accessors Needs a Third Tool
Neither tool preserves getters. Both read the getter once and store the result as a plain value. To copy property descriptors exactly, use Object.getOwnPropertyDescriptors together with Object.defineProperties or Object.create.
let count = 0;
const source = { get next() { return ++count; } };
const a = { ...source };
const b = Object.assign({}, source);
console.log(a.next, b.next); // 1 2 (each tool called the getter once)
console.log(a.next, b.next); // 1 2 (now frozen values)
const c = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
console.log(c.next, c.next); // 3 4 (live getter preserved)
const clone = Object.create(
Object.getPrototypeOf(source),
Object.getOwnPropertyDescriptors(source)
);
console.log(clone.next); // 5The Object.create form also keeps the prototype, so you can use it for a shallow clone of a class instance.
Merging a Dynamic List of Objects
When the number of sources is only known at runtime, Object.assign with a spread argument list does the merge in a single pass:
const layers = [{ a: 1 }, { b: 2 }, { a: 3, c: 4 }];
const merged = Object.assign({}, ...layers);
console.log(merged); // { a: 3, b: 2, c: 4 }
// Same result, but copies the growing accumulator on every step
const slowMerged = layers.reduce((acc, layer) => ({ ...acc, ...layer }), {});
console.log(slowMerged); // { a: 3, b: 2, c: 4 }The reduce version recopies the accumulator on each step, so its total work grows with the square of the number of properties. For a few objects this does not matter. For hundreds of layers, use Object.assign({}, ...layers) or { ...layers } written per layer in a loop that mutates one accumulator. For single copies, the two tools perform about the same, so speed should not drive the choice.
Choosing Between Them
| Situation | Prefer | Reason |
|---|---|---|
| Copy or merge plain data into a new object | Spread | Shorter, never mutates, never calls setters |
| Optional sources that may be `null` or `undefined` | Spread | No target to fail |
| Copying parsed JSON or other untrusted input | Spread | `__proto__` stays a harmless own property |
| Updating an existing object in place, such as `Object.assign(this, options)` in a constructor | `Object.assign` | Mutation is the goal, and setters run |
| Target has setters that validate or transform | `Object.assign` | Spread bypasses setters |
| Merging an array of objects of unknown length | `Object.assign({}, ...list)` | One pass, no repeated copying |
| Preserving getters, setters or the prototype | `getOwnPropertyDescriptors` with `Object.create` | Neither tool copies descriptors |
| Code must run on pre-ES2018 engines without a transpiler | `Object.assign` | Available since ES2015 |
Exercise
An Account class has a balance setter that rejects negative numbers. A teammate updates an account with const next = { ...account, balance: -50 }; and then calls next.deposit(10). What happens, and how should the update be written?
Show answer
The spread creates a plain object whose prototype is Object.prototype. The balance setter never runs, so -50 is stored without validation. deposit lives on Account.prototype and is missing, so next.deposit(10) throws a TypeError ("next.deposit is not a function"). To go through the setter on the same instance, write Object.assign(account, { balance: -50 }), which calls the setter and lets it reject the value. If you need a separate copy, build a new Account, for example with Object.create(Object.getPrototypeOf(account), Object.getOwnPropertyDescriptors(account)) followed by Object.assign on the clone. Note that private fields are not copied that way, so a constructor or a clone method is safer for classes with private state.
Exercise
Predict the output: const cfg = Object.freeze({ mode: 'a' }); const x = { ...cfg, mode: 'b' }; const y = Object.assign({}, cfg, { mode: 'c' }); console.log(x.mode, y.mode, Object.isFrozen(x)); Object.assign(cfg, { mode: 'd' });
Show answer
The log prints b c false. Both x and y are new, unfrozen objects, so overriding mode works. The last line throws a TypeError because Object.assign tries to Set mode on the frozen cfg, and Object.assign throws on failed writes even in non-strict code.
Exercise
Why does Object.assign({}, JSON.parse('{"__proto__": {"role": "admin"}}')).role evaluate to 'admin', while the same expression using { ...JSON.parse(...) } evaluates to undefined?
Show answer
JSON.parse makes "_proto" an ordinary own property. Object.assign copies it with [[Set]], which calls the inherited proto setter and replaces the target's prototype with { role: 'admin' }, so role is inherited. Spread uses CreateDataProperty, which creates an own property literally named "proto_" and leaves the prototype as Object.prototype, so role is undefined.