Overview
Use the three dots to copy arrays and objects, merge user settings over defaults and collect leftover fields.
- Spread copies into a new array or object
- The last key wins when merging
- Rest collects what's left
Short Course
Spread ... copies items or fields into a new array or object; rest
... gathers what's left. Trap: when merging, the last key wins, so put
the defaults first.
const base = { color: "red", size: 1 };
const merged = { ...base, size: 2 }; // { color: "red", size: 2 }
const wrong = { size: 2, ...base }; // { size: 1, color: "red" }
const nums = [...[1, 2], 3]; // [1, 2, 3]
const { color, ...others } = merged; // others = { size: 2 }
Task
Write withDefaults(options) that returns a new object with options merged
onto { theme: "light", size: 14 }, for example withDefaults({ theme: "dark" })
gives { theme: "dark", size: 14 }.
Test Suites
Pending
Next
Output