Latticework

Command Palette

Search for a command to run...

JavaScript

Objects & Arrays

14 min

Explanation

The spread operator (...) copies an object or array's own properties into a new one: { ...base, c: 3 } makes a NEW object with all of base's keys plus cbase itself is untouched. When two spread sources share a key, whichever comes LAST in the literal wins. Array destructuring can skip elements with a blank slot: const [a, , c] = [1, 2, 3] skips index 1 entirely.

const DEFAULTS = { theme: "dark", volume: 5 };
function mergeDefaults(overrides) {
  return { ...DEFAULTS, ...overrides };
}
console.log(mergeDefaults({ volume: 8 }));
// { theme: "dark", volume: 8 } -- DEFAULTS itself is unchanged
Try it

extended is a brand-new object -- base still only has {a, b}. The array destructure grabs index 0 and index 2, skipping index 1 with the empty slot between commas.

Loading editor…
Exercise

A `DEFAULTS` object `{ theme: "dark", volume: 5 }` already exists. Write `mergeDefaults(overrides)` that returns a NEW object — `DEFAULTS` with `overrides` layered on top (overrides win on conflicting keys) — using object spread, without mutating `DEFAULTS` itself.

Quiz

In `{ ...DEFAULTS, ...overrides }`, if both objects have a `volume` key, which one wins?

Checkpoint

You can merge objects with spread (without mutating the originals) and skip elements when destructuring arrays.