Objects & Arrays
14 min
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 c — base 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
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.
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.
In `{ ...DEFAULTS, ...overrides }`, if both objects have a `volume` key, which one wins?
You can merge objects with spread (without mutating the originals) and skip elements when destructuring arrays.