The challenge
Write withDefaults(options) that returns a new object containing these defaults, overridden by anything in options: { theme: "light", sound: true, volume: 50 }.
withDefaults({ volume: 80 })
// { theme: "light", sound: true, volume: 80 }
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
withDefaults({ volume: 80 })gives{ theme: "light", sound: true, volume: 80 }withDefaults({})gives{ theme: "light", sound: true, volume: 50 }withDefaults({ theme: "dark", sound: false })gives{ theme: "dark", sound: false, volume: 50 }
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
The spread syntax copies objects: { ...a, ...b }. Later properties win.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function withDefaults(options) {
const defaults = { theme: "light", sound: true, volume: 50 };
return { ...defaults, ...options };
}
Learn what you need
This exercise uses what Grade 8: Objects: Describing Things With Labels teaches. Read those notes first if any of it is new.