Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Object.assign vs spread in JavaScript

36 Object.assign against object spread

hard

Copy properties two ways and separate the two behaviours: which one mutates its target, which one triggers a setter, what each does with a getter, and what each does with null.

Stuck? Three hints, smallest first
  1. 1. Object.assign(target, source) writes into target and returns it. Spread always builds a new plain object.
  2. 2. Assign writes with [[Set]], so a setter on the target intercepts it. Spread defines plain data properties on a fresh object.
  3. 3. Both read only own enumerable properties, and both read a getter rather than copying it.

The answer

const attempt = (fn) => {
  try { return fn(); } catch (e) { return e.constructor.name; }
};

const target = { a: 1 };
const returned = Object.assign(target, { b: 2 });
const spreadOut = { ...target, c: 3 };            // target must not change

const written = [];
const holder = {
  _v: 'fixed',
  get name() { return this._v; },
  set name(value) { written.push(value); },        // deliberately does not store
};
Object.assign(holder, { name: 'Ngozi' });
const snapshot = { ...holder };

const proto = { inherited: 'from the prototype' };
const child = Object.create(proto);
child.own = 'own value';
const spreadChild = { ...child };

const assignNull = attempt(() => Object.assign(null, { a: 1 }));
const spreadNull = { ...null, ...undefined };

console.log('assign returns its target:', returned === target, target);
console.log('spread leaves it alone   :', Object.keys(target), '->', spreadOut);
console.log('setter saw               :', written, '| holder.name still', holder.name);
console.log('spread snapshot          :', snapshot.name, 'as a plain value');
console.log('inherited                :', spreadChild);
console.log('null                     :', assignNull, '|', spreadNull);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('Object.assign mutates its first argument and returns it', returned === target, true);
test('so the target now carries both keys', target, { a: 1, b: 2 });
test('spread builds a new object and leaves the source untouched', [Object.keys(target).length, spreadOut.c], [2, 3]);
test('assign writes through a setter on the target', written, ['Ngozi']);
test('and the setter kept control, so nothing was stored', holder.name, 'fixed');
test('spread reads a getter once and stores the result as data', [snapshot.name, Object.getOwnPropertyDescriptor(snapshot, 'name').writable], ['fixed', true]);
test('both ignore inherited properties', spreadChild, { own: 'own value' });
test('and a spread copy is always a plain object', Object.getPrototypeOf(spreadChild) === Object.prototype, true);
test('assign refuses null as a target, while spreading null is harmless', [assignNull, spreadNull], ['TypeError', {}]);

Prefer spread. It cannot mutate anything by accident, it is shorter, and it always produces a plain object. Reach for Object.assign only when mutating an existing object is the point — topping up a config in place, or writing onto this in a constructor.

The setter assertion is the difference that bites. Object.assign assigns, so every setter, and every Object.defineProperty guard on the target, gets a say. Spread defines, so a getter/setter pair on the source is flattened into an ordinary writable value and the accessor is gone. Neither is a faithful copy of a property's definition; for that you need Object.getOwnPropertyDescriptors with Object.defineProperties.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.