JavaScript · Level 2 Objects

Destructuring

Pull the fields you need straight out of objects and arrays, give them fallback values and unpack them right in a function's parameters.

  • Object destructuring { name }
  • Array destructuring [first, second]
  • Default values with =
  • Destructuring in parameters

Destructuring copies fields into variables in one line, and works in function parameters too. Trap: a default (= value) only applies when the field is undefined, not when it is 0, "" or null.

const user = { name: "Ada", role: "admin" };
const { name, city = "Paris" } = user;   // name "Ada", city "Paris"
const [first, second] = ["red", "blue"]; // first "red", second "blue"

function hi({ name }) { return `Hi ${name}`; }
hi(user);                                // "Hi Ada"

Write formatUser({ name, age = "?" }) that returns "<name> (<age>)", for example formatUser({ name: "Bob" }) returns Bob (?).

solution.js
Test Suites Pending
Output