Emmanuel Akinfulubi

JavaScriptBasic

Merge objects with default values in JavaScript

Intermediate · 3 min read

Many functions take an "options" object. The caller passes only the settings they care about, and the function fills in the rest from a set of defaults. A booking form, a chart library and a request helper all work this way. The job is to merge two objects so that anything the caller passed wins, and anything they left out comes from the defaults.

In this tutorial you will merge a defaults object with a booking using the spread syntax ... and with Object.assign. Then you will see what "shallow" means, when changing a copy also changes the original. You need to know what an object is.

Spread copies keys into a new object

Inside an object literal, ...obj copies every key of obj into the new object:

JavaScript

const a = { fare: 200_00, tier: 'economy' };
const copy = { ...a };
console.log(copy); // { fare: 20000, tier: 'economy' }

200_00 is 20,000 kobo, which is ₦200; the underscore only helps you read it. You can spread more than one object. They are copied left to right, and when two of them have the same key, the later one overwrites the earlier one. That left-to-right rule is the whole trick for defaults.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

86 Merge defaults with what the caller passed

fair

Merge a defaults object with a caller's object so the caller wins. Do it with spread and with Object.assign, then show what "shallow" means by changing a nested value.

Stuck? Three hints, smallest first
  1. 1. In { ...a, ...b } the later object wins on any shared key.
  2. 2. Object.assign(target, source) changes target and returns it.
  3. 3. Both copy one level deep. A nested object is shared, not copied.

Step 1: defaults first, caller last

Step 1

const defaults = { fare: 200_00, tier: 'economy', ac: false };
const booking = { fare: 350_00, ac: true };
const merged = { ...defaults, ...booking };
console.log(merged); // { fare: 35000, tier: 'economy', ac: true }

The defaults are copied first, then the booking is copied on top. fare and ac come from the booking. tier wasn't in the booking, so the default stays.

Step 2: the wrong way round

Swap the order and the bug is silent:

Step 2

const defaults = { fare: 200_00, tier: 'economy', ac: false };
const booking = { fare: 350_00, ac: true };
const wrongWayRound = { ...booking, ...defaults };
console.log(wrongWayRound.fare); // 20000
console.log(wrongWayRound.ac);   // false

Now every default overwrites what the caller asked for. Nothing throws. The customer paid for air conditioning and doesn't get it. Remember: defaults go first.

Step 3: the key order

Step 3

const defaults = { fare: 200_00, tier: 'economy', ac: false };
const booking = { ac: true, fare: 350_00 };
console.log(Object.keys({ ...defaults, ...booking })); // [ 'fare', 'tier', 'ac' ]

A key keeps the position where it first appeared. A later object changes the value, not the position. That is handy: the merged object always lists its keys in the same order as the defaults.

Step 4: Object.assign changes its first argument

Object.assign(target, source) copies the keys of source onto target. Unlike spread, it doesn't make a new object. It changes target and returns that same object:

Step 4

const defaults = { fare: 200_00, tier: 'economy', ac: false };
const booking = { fare: 350_00, ac: true };
const target = { ...defaults };
const returned = Object.assign(target, booking);
console.log(returned === target); // true
console.log(target.fare);         // 35000

That's fine here, because target is a fresh copy made one line earlier. It would be a bug to write Object.assign(defaults, booking): the shared defaults would now hold this one customer's choices, and every later booking would start from them. The safe spelling is Object.assign({}, defaults, booking).

Step 5: what "shallow" means

Both spread and Object.assign copy one level. If a value is itself an object, the copy gets the same inner object, not a new one:

Step 5

const base = { route: { from: 'Yaba', to: 'Ikeja' }, fare: 200_00 };
const copy = { ...base };
copy.route.to = 'Lekki';
copy.fare = 500_00;
console.log(base.route.to); // Lekki
console.log(base.fare);     // 20000

Changing copy.fare left base.fare alone, because numbers are copied. Changing copy.route.to changed the original, because base.route and copy.route are one and the same object. For a full, deep copy, use structuredClone(base).

Step 6: undefined still overwrites

One more surprise. A key that is present with the value undefined still counts:

Step 6

const defaults = { fare: 200_00, tier: 'economy', ac: false };
const blanked = { ...defaults, tier: undefined };
console.log(blanked.tier); // undefined

This happens when you build options from a form where a field was left empty. Remove those keys before merging, or use ?? where you read the value.

The full solution

The answer panel merges the booking over the defaults both ways round, uses Object.assign and checks it returned the same object, shows the shared nested route, and shows undefined overwriting a default. Press Run to see the output.

The answer

const defaults = { fare: 200_00, tier: 'economy', ac: false };
const booking = { fare: 350_00, ac: true };

const merged = { ...defaults, ...booking };          // the caller wins
const wrongWayRound = { ...booking, ...defaults };   // the defaults win, which is a bug

// Object.assign mutates its first argument and hands the same object back.
const target = { ...defaults };
const returned = Object.assign(target, booking);

// Shallow: the nested route object is shared between base and copy.
const base = { route: { from: 'Yaba', to: 'Ikeja' }, fare: 200_00 };
const copy = { ...base };
copy.route.to = 'Lekki';
copy.fare = 500_00;

// An explicit undefined still counts as a value and overwrites.
const blanked = { ...defaults, tier: undefined };

console.log(merged);
console.log('base after editing the copy:', JSON.stringify(base));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the later object wins', merged, { fare: 35000, tier: 'economy', ac: true });
test('order matters: reversed, the defaults overwrite the booking', wrongWayRound.fare, 20000);
test('Object.assign returns the very object it changed', returned === target, true);
test('so the first argument was mutated', target.fare, 35000);
test('spread copies one level, so the nested route is shared', base.route.to, 'Lekki');
test('a top-level value is independent, though', base.fare, 20000);
test('an explicit undefined overwrites a real default', blanked.tier, undefined);
test('key order follows first appearance, not the later object', Object.keys(merged), ['fare', 'tier', 'ac']);

Spread reads left to right and the last write wins, so defaults go first and the caller's object last. Reversing that is a common and quiet bug: every value the caller passed is silently replaced by a default, and nothing throws. Object.assign(target, source) does the same job but mutates target — fine when you built the target yourself two lines earlier, dangerous when the target is something you were handed. Object.assign({}, a, b) is the safe spelling.

"Shallow" is the trap worth remembering: base.route and copy.route are one object, so editing the copy changed the original. Only the top level is duplicated. A nested merge needs structuredClone or a deliberate deep merge (exercise 40). And tier: undefined overwriting the default catches people building option objects from optional inputs — filter those keys out first, or use ?? at the point of use.

Common mistakes

  • Putting the defaults last. { ...booking, ...defaults } throws away everything the caller passed.
  • Calling Object.assign(defaults, ...). It changes the shared defaults object. Start from {}.
  • Expecting a deep copy. Nested objects are shared between the original and the copy.

Try it yourself

  1. Write withDefaults(options) that returns { ...defaults, ...options }, and call it with {} and with { tier: 'luxury' }.
  2. Give defaults a nested route object and show that two merged bookings share it. Then fix it with structuredClone.
  3. Write dropUndefined(obj) with Object.entries, filter and Object.fromEntries, and use it before merging so tier: undefined keeps the default.

Keep practising

Newsletter

New writing, when it lands.

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