Sub topic 12
Options Objects with Destructured Parameters
This chapter assumes you already know object destructuring syntax, default parameter values, and the rule from earlier chapters that defaults apply only when a value is undefined. It shows how to combine those three ideas into a function signature that takes named, optional settings.
Why Use an Options Object
Positional parameters work well for one or two values. Past that, call sites become hard to read, and callers have to fill in values they don't care about:
function createUserPositional(name, role, active, notify) {
return { name, role, active, notify };
}
// What do true and false mean here? The caller has to check the signature.
console.log(createUserPositional("Ana", undefined, true, false));An options object fixes this. The caller passes one object whose property names label each value. Properties can be given in any order, and any of them can be left out.
| Concern | Positional parameters | Options object |
|---|---|---|
| Readability at call site | Meaning depends on position | Each value is named |
| Skipping a middle value | Must pass `undefined` | Leave the property out |
| Adding a new setting later | Order is fixed, so new settings go at the end | Add a property anywhere |
| Typo in a name | Not possible | Silently ignored (see below) |
| Best for | 1–3 required, obvious values | Several optional settings |
A common hybrid keeps required values positional and puts optional settings in a trailing options object: fetch(url, { method, headers }).
The Basic Pattern
Destructure the object directly in the parameter list, and give each property its own default:
function createUser({ name, role = "viewer", active = true } = {}) {
return { name, role, active };
}
console.log(createUser({ name: "Ana", role: "admin" }));
// { name: "Ana", role: "admin", active: true }
console.log(createUser({ name: "Bo" }));
// { name: "Bo", role: "viewer", active: true }
console.log(createUser());
// { name: undefined, role: "viewer", active: true }This signature uses two separate layers of defaults:
- Per-property defaults (
role = "viewer",active = true) apply when that property is missing orundefinedon the object passed in. - The whole-parameter default (
= {}) applies when no object is passed at all. It hands an empty object to the destructuring step, which then fills every property from its own default.
Common Error: Forgetting the `= {}`
Without the whole-parameter default, calling the function with no argument means destructuring undefined. That throws:
function connect({ host = "localhost", port = 5432 }) {
return `${host}:${port}`;
}
console.log(connect({ port: 3000 })); // "localhost:3000"
try {
connect();
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "Cannot destructure property 'host' of 'undefined' ..."
}The per-property defaults don't help here. They only run after destructuring has something to read from. If every option is optional, add = {}.
Edge Case: Passing `null`
The = {} default follows the undefined-only rule, so null gets past it and the destructuring step throws:
function createUser({ name, role = "viewer" } = {}) {
return { name, role };
}
try {
createUser(null);
} catch (err) {
console.log(err instanceof TypeError); // true
}If callers might pass null (for example, values that come from JSON or a database), take the object as a plain parameter and destructure it inside the body with ??:
function createUserSafe(options) {
const { name, role = "viewer", active = true } = options ?? {};
return { name, role, active };
}
console.log(createUserSafe(null)); // { name: undefined, role: "viewer", active: true }The same rule applies to individual properties: { role: null } leaves role as null because null isn't undefined, so the default doesn't run.
Renaming While Destructuring
You can bind a property to a different local name and still give it a default. The syntax is property: localName = default:
function wait({ timeout: ms = 1000 } = {}) {
return `waiting ${ms}ms`;
}
console.log(wait({ timeout: 250 })); // "waiting 250ms"
console.log(wait()); // "waiting 1000ms"The caller still uses the public name timeout. Only the function body sees ms. Note that timeout itself is not defined as a variable inside the function.
Nested Options
Options can contain sub-objects. Each nested level needs its own = {} for the same reason the top level does:
function request({
url,
method = "GET",
retry: { attempts = 3, delay = 100 } = {},
} = {}) {
return { url, method, attempts, delay };
}
console.log(request({ url: "/api" }));
// { url: "/api", method: "GET", attempts: 3, delay: 100 }
console.log(request({ url: "/api", retry: { attempts: 5 } }));
// { url: "/api", method: "GET", attempts: 5, delay: 100 }If you remove = {} after the retry pattern, request({ url: "/api" }) throws, because it tries to destructure undefined as retry. Also note that retry is a pattern here, not a variable. Use attempts and delay in the body.
Catching Typos and Passing Extra Options Along
Unknown properties are silently ignored. createUser({ nmae: "Ana" }) returns name: undefined with no warning. Use a rest element to collect whatever wasn't destructured. You can then check those extra keys or forward them to another function:
function createButton({ label = "OK", size = "medium", ...rest } = {}) {
const unknown = Object.keys(rest);
if (unknown.length > 0) {
throw new Error(`Unknown option(s): ${unknown.join(", ")}`);
}
return { label, size };
}
console.log(createButton({ label: "Save" })); // { label: "Save", size: "medium" }
try {
createButton({ lable: "Save" });
} catch (err) {
console.log(err.message); // "Unknown option(s): lable"
}Whether to reject unknown keys depends on the function. Strict checking suits public APIs. Forwarding rest suits wrapper functions that pass extra options down to a lower layer.
Making an Option Required
Default expressions run only when they are needed, so the throwing-default pattern from the earlier "Enforcing Required Parameters" chapter works on individual properties too:
function required(name) {
throw new Error(`Missing option: ${name}`);
}
function openFile({ path = required("path"), mode = "r" } = {}) {
return `${path} (${mode})`;
}
console.log(openFile({ path: "notes.txt" })); // "notes.txt (r)"
try {
openFile();
} catch (err) {
console.log(err.message); // "Missing option: path"
}Effect on `function.length`
A destructured parameter counts as one parameter. Giving it a default (= {}) means it is no longer counted, as with any parameter that has a default:
function a({ x }) {}
function b({ x } = {}) {}
function c(id, { x } = {}) {}
console.log(a.length, b.length, c.length); // 1 0 1This matters only for code that inspects length, such as some currying helpers or test frameworks.
Exercise
Given function setup({ debug = false, level = "info" } = {}) { return [debug, level]; }, what do these calls return or throw: setup(), setup({ debug: null }), setup({ level: undefined }), and setup(null)?
Show answer
setup() returns [false, "info"] because the = {} default applies. setup({ debug: null }) returns [null, "info"] because null is not undefined, so the debug default doesn't run. setup({ level: undefined }) returns [false, "info"] because an explicit undefined triggers the default. setup(null) throws a TypeError: the = {} default doesn't apply to null, and null can't be destructured.
Exercise
Rewrite function render(el, opts = { color: "black", size: 12 }) { return ${opts.color}/${opts.size}; } so that render(el, { size: 20 }) returns "black/20" and render(el) returns "black/12".
Show answer
Move the defaults onto the individual properties: function render(el, { color = "black", size = 12 } = {}) { return ${color}/${size}; }. In the original version, passing { size: 20 } replaces the whole default object, so color is undefined. Per-property defaults fill in each missing option on its own.