easyJS ES6+#67

Destructuring and default params

Prompt

Create a function createUser that takes an object with name and email, with defaults: { name: 'Anonymous', email: 'unknown@example.com' }. Use destructuring in the function signature. Calling createUser() with no arguments must also work.

Solution

function createUser({ name = 'Anonymous', email = 'unknown@example.com' } = {}) {
  return { name, email }
}
Mentor's take

This one-liner is really an API-design question: a destructured options object gives you named, order-independent, individually defaultable parameters — the reason nearly every modern library takes (options) instead of five positional arguments. The signature does two distinct jobs, and interviewers check that you know they're different.

Per-property defaults (name = 'Anonymous') fire only when the property is undefined — a missing key or an explicit undefined. They do not fire for null, '', or 0; createUser({ name: null }) returns { name: null }. That's a feature: default parameters distinguish "not provided" from "provided as empty," which name || 'Anonymous' cannot.

The outer = {} is the part juniors miss. Destructuring is an operation on a value — destructuring undefined throws TypeError: Cannot destructure property. Without the outer default, createUser() with no argument crashes before your first line runs. = {} substitutes an empty object, every property comes up undefined, and every inner default engages.

Red flag: "fixing" the no-arg crash with options = options || {} inside the body plus manual property checks. It works, but it reintroduces the falsy-value bug (0 and '' get overwritten) and signals you don't know the signature can express the whole contract.

Say it: "Defaults trigger on undefined only — not null or falsy — and the outer = {} exists because destructuring undefined throws, so the no-argument call must have something to destructure."