Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Merge objects with spread: which key wins in JavaScript

28 Merging objects, and which key wins

fair

Merge defaults with caller-supplied options using object spread. Establish which side wins, what a literal key next to a spread does, and what an explicit undefined in the caller's object does to your default.

Stuck? Three hints, smallest first
  1. 1. Later wins. { ...defaults, ...given } lets given override.
  2. 2. A literal key participates in the same left-to-right order as the spreads around it.
  3. 3. A property whose value is undefined is still a property, so it still overrides.

The answer

const defaults = { branch: 'Ikeja', currency: 'NGN', discount: 0 };
const given = { branch: 'Yaba', discount: undefined };

const merged = { ...defaults, ...given };
const reversed = { ...given, ...defaults };
const literalAfter = { ...defaults, branch: 'Lekki' };
const literalBefore = { branch: 'Lekki', ...defaults };

const clean = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));
const cleaned = { ...defaults, ...clean };

const viaAssign = Object.assign({}, defaults, given);

console.log('merged        :', merged, '<- discount is gone from the log');
console.log('key list      :', Object.keys(merged), '<- but the key is there');
console.log('reversed      :', reversed.branch);
console.log('literal after :', literalAfter.branch, '| before:', literalBefore.branch);
console.log('cleaned       :', cleaned);
console.log('Object.assign :', viaAssign.branch);

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('the later spread wins', merged.branch, 'Yaba');
test('swap the order and the other side wins', reversed.branch, 'Ikeja');
test('a literal key after a spread overrides it', literalAfter.branch, 'Lekki');
test('a literal key before a spread is overridden by it', literalBefore.branch, 'Ikeja');
test('an explicit undefined overrides the default too', merged.discount === undefined, true);
test('the key really is present, whatever JSON shows', ['discount' in merged, JSON.stringify(merged).includes('discount')], [true, false]);
test('keys keep first-seen order regardless of which side supplied the value', Object.keys(merged), ['branch', 'currency', 'discount']);
test('dropping the undefined values first preserves the default', cleaned.discount, 0);
test('Object.assign into a fresh object merges identically', viaAssign.branch, 'Yaba');

The undefined case is the trap, and it is common: a caller builds an options object from variables, one of them is unset, and the property arrives as undefined. Spread does not care that the value is missing — it is a key, it is later, it wins, and your default is gone. Note the assertion that JSON.stringify hides it: the log looks like the key was never there.

Two fixes. Filter the undefined values out before merging, as above, or destructure with defaults instead — const { discount = 0 } = given fires on undefined, which is precisely the case spread gets wrong.

Newsletter

New writing, when it lands.

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