Sub topic 9
Destructuring Function Parameters and Options Objects
A function parameter can be a destructuring pattern instead of a plain name. The pattern unpacks the argument as soon as the function is called. This chapter shows how to use that to build functions that take an options object: one argument whose properties are named, optional settings.
This chapter assumes you can already destructure objects and arrays, rename properties, set default values, and use rest properties in patterns. Earlier chapters covered all of these.
From positional arguments to named options
Here is a function that takes several positional parameters:
function createServer(host, port, secure, timeout) {
return { host, port, secure, timeout };
}
// Which argument is which? The call site does not say.
console.log(createServer('localhost', 8080, false, 3000));Positional arguments cause three problems. Callers must remember the order. Skipping a middle argument means passing undefined explicitly. Adding a parameter later can break existing calls.
An options object fixes all three, because each value is labeled by its property name:
function createServer({ host, port, secure, timeout }) {
return { host, port, secure, timeout };
}
console.log(createServer({ port: 8080, host: 'localhost' }));
// { host: 'localhost', port: 8080, secure: undefined, timeout: undefined }The parameter { host, port, secure, timeout } works exactly like const { host, port, secure, timeout } = argument; would at the top of the function body. Property order in the call no longer matters.
Per-property defaults and the whole-object default
Most options should have sensible defaults. Put them inside the pattern:
function connect({ host = 'localhost', port = 5432 } = {}) {
return `${host}:${port}`;
}
console.log(connect()); // 'localhost:5432'
console.log(connect({ port: 6543 })); // 'localhost:6543'
console.log(connect({ host: 'db', port: 1 })); // 'db:1'This signature has two layers of defaults, and each one does a different job:
| Default | Where it sits | What it handles |
|---|---|---|
| `host = 'localhost'` | Inside the pattern | The caller passed an object without `host` (or with `host: undefined`) |
| `= {}` after the pattern | On the whole parameter | The caller passed no argument at all |
The outer = {} is easy to forget. Without it, calling the function with no argument means destructuring undefined, and that throws:
function connectStrict({ host = 'localhost', port = 5432 }) {
return `${host}:${port}`;
}
try {
connectStrict();
} catch (err) {
console.log(err instanceof TypeError); // true
}Defaults are expressions, evaluated left to right
A default can be any expression. JavaScript evaluates it only when it is needed, and it evaluates the pattern from left to right. That means a later default can refer to an earlier property:
function range({ start = 0, end = start + 10, step = 1 } = {}) {
const result = [];
for (let i = start; i < end; i += step) result.push(i);
return result;
}
console.log(range({ start: 5, step: 2 })); // [5, 7, 9, 11, 13]
console.log(range({ end: 3 })); // [0, 1, 2]If you reverse the order, so that start defaults to end, reading end before it is initialized throws a ReferenceError.
Because defaults are evaluated lazily, you can use one to mark an option as required:
function required(name) {
throw new Error(`Missing required option: ${name}`);
}
function createUser({ name = required('name'), role = 'member' } = {}) {
return { name, role };
}
console.log(createUser({ name: 'Ada' })); // { name: 'Ada', role: 'member' }
try {
createUser({ role: 'admin' });
} catch (err) {
console.log(err.message); // 'Missing required option: name'
}required('name') runs only when name is undefined, so callers who pass a name never trigger it.
Renaming and rest inside parameters
Everything you can do in a destructuring declaration also works in a parameter. Renaming helps when the public option name would clash with a local variable or reads poorly inside the function:
function formatPrice({ amount, currency: code = 'USD' }) {
return `${amount.toFixed(2)} ${code}`;
}
console.log(formatPrice({ amount: 9.5 })); // '9.50 USD'
console.log(formatPrice({ amount: 3, currency: 'EUR' })); // '3.00 EUR'A rest property lets a function take the options it understands and pass everything else along untouched. Wrapper functions use this a lot:
function request(url, { timeout = 5000, retries = 0, ...fetchOptions } = {}) {
return { url, timeout, retries, fetchOptions };
}
console.log(request('/api', { method: 'POST', retries: 2, headers: { a: '1' } }));
// {
// url: '/api',
// timeout: 5000,
// retries: 2,
// fetchOptions: { method: 'POST', headers: { a: '1' } }
// }This example also shows a common shape: required values stay positional (url), and optional settings go into a trailing options object.
Destructuring array parameters
Array patterns work in parameters too. They show up most often in callbacks, where each element is itself a pair or tuple:
const prices = { apple: 1.2, pear: 0.8 };
const lines = Object.entries(prices).map(([fruit, price]) => `${fruit}: ${price}`);
console.log(lines); // ['apple: 1.2', 'pear: 0.8']
function distance([x1, y1], [x2, y2]) {
return Math.hypot(x2 - x1, y2 - y1);
}
console.log(distance([0, 0], [3, 4])); // 5Arrow functions and destructured parameters
An arrow function with a destructured parameter always needs parentheses around its parameter list, even when there is only one parameter:
const area = ({ width, height = width }) => width * height;
console.log(area({ width: 4 })); // 16
console.log(area({ width: 4, height: 2 })); // 8{ width } => ... without the parentheses is a syntax error.
Effects on `function.length`
A function's length property counts the parameters that come before the first one with a default or a rest. A destructured parameter counts like any other parameter, but adding the outer = {} stops the count:
function a({ x }) {}
function b({ x } = {}) {}
function c(id, { x } = {}) {}
console.log(a.length); // 1
console.log(b.length); // 0
console.log(c.length); // 1Most code never reads length. Some libraries do, such as currying helpers and some test frameworks that check whether a callback takes a done argument. If you use one of them, keep this rule in mind.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Missing outer `= {}` | `fn()` throws a TypeError | Add `= {}` after the pattern |
| Default written as `{ a } = { a: 1 }` and the caller passes `{}` | `a` is `undefined`, because the default object is ignored when an argument is given | Put defaults on each property: `{ a = 1 } = {}` |
| Passing `null` for "no options" | TypeError | Pass `undefined` or nothing, or normalize the argument first |
| Defaults that depend on a later property | ReferenceError | Reorder the pattern so dependencies come first |
| No parentheses around an arrow parameter pattern | SyntaxError | Write `({ a }) => ...` |
The second row catches many people. function f({ a } = { a: 1 }) gives a = 1 only for f(). For f({}), the caller's empty object replaces the whole default, so a is undefined.
Exercises
Exercise
Given function f({ size } = { size: 10 }) { return size; }, what do f(), f({}), and f({ size: 3 }) return, and why?
Show answer
f() returns 10, because the whole-object default { size: 10 } is used. f({}) returns undefined, because an argument was given, so the default object is ignored and {} has no size. f({ size: 3 }) returns 3. To get 10 in the second case, write function f({ size = 10 } = {}).
Exercise
Write a function greet that takes an options object with name (required) and greeting (default 'Hello'), returns a string like 'Hello, Ada!', throws an Error mentioning 'name' when name is missing, and can be called with no arguments without a TypeError from destructuring.
Show answer
function required(n) { throw new Error('Missing required option: ' + n); } then function greet({ name = required('name'), greeting = 'Hello' } = {}) { return ${greeting}, ${name}!; }. Calling greet() uses the {} default and then throws the custom 'Missing required option: name' Error instead of a TypeError.
Exercise
What do retries and rest contain after calling function g({ retries = 1, ...rest } = {}) { return [retries, rest]; } as g({ retries: undefined, mode: 'fast' })?
Show answer
retries is 1, because the passed value is undefined and the default applies. rest is { mode: 'fast' }. The rest property collects only the properties the pattern did not name, so retries is left out.