Merge default settings with user options

“Default settings”, a Green belt challenge from the CurlyScript Dojo. It uses what Grade 8: Objects: Describing Things With Labels teaches, and 3 tests check your answer.

The challenge

Write withDefaults(options) that returns a new object containing these defaults, overridden by anything in options: { theme: "light", sound: true, volume: 50 }.

Example
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.

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
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.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning