Sub topic 9
Destructuring Function Parameters and Options Objects
This chapter assumes you already know object destructuring, default values in patterns, and rest properties from earlier chapters. Here you apply those same patterns directly in a function's parameter list.
Patterns in the Parameter List
A parameter can be a destructuring pattern instead of a plain name. JavaScript destructures the argument as it binds the parameters, the same way const { a } = arg works.
function greet({ name, title }) {
return `Hello, ${title} ${name}`;
}
console.log(greet({ name: 'Lovelace', title: 'Countess' })); // 'Hello, Countess Lovelace'The function body never sees the whole object. It works only with the variables it asked for, so the signature also documents which properties the function reads.
The Options Object Pattern
Many functions take a handful of optional settings. Positional parameters make callers remember the order and pass undefined to skip a setting. An options object with per-property defaults removes both problems:
function connect({ host = 'localhost', port = 5432 } = {}) {
return `${host}:${port}`;
}
console.log(connect()); // 'localhost:5432'
console.log(connect({ port: 6543 })); // 'localhost:6543'The defaults work at two levels:
- The
= {}after the pattern is the default for the whole parameter. It applies when the caller passes nothing. host = 'localhost'andport = 5432are defaults for individual properties. They apply when a property is missing from the object.
The Most Common Error: Forgetting `= {}`
If you leave out the whole-parameter default, calling the function with no arguments 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
}Mixing Positional and Options Parameters
A common signature puts required values first as positional parameters and optional settings last in an options object. A rest property can collect any options the function doesn't handle itself, so it can pass them along:
function request(url, { method = 'GET', timeout = 5000, ...extra } = {}) {
return { url, method, timeout, extra };
}
console.log(request('/users'));
// { url: '/users', method: 'GET', timeout: 5000, extra: {} }
console.log(request('/users', { method: 'POST', headers: { a: 1 } }));
// { url: '/users', method: 'POST', timeout: 5000, extra: { headers: { a: 1 } } }Choosing a Signature
| Situation | Prefer |
|---|---|
| One or two required, obvious arguments | Positional parameters |
| Several optional settings | Options object with defaults |
| Boolean flags (`true, false, true`) | Options object, so calls are self-describing |
| Settings forwarded to another API | Options object with a rest property |
Options objects make it easy to add a new setting without breaking existing calls. The cost is a little more syntax, and typos in property names fail silently: { prot: 6543 } just falls back to the default port.
Exercise
Given function resize({ width = 100, height = width } = {}) { return [width, height]; }, what do resize(), resize({ width: 40 }), and resize({ height: undefined, width: 0 }) return?
Show answer
[100, 100], [40, 40], and [0, 0]. Defaults are evaluated left to right, so height can use width. An undefined height triggers its default, and 0 is a real value, so width keeps it.
Exercise
Why does function f({ a = 1 }) {} throw when called as f(), and what one-token change to the signature fixes it?
Show answer
With no argument, the parameter is undefined, and destructuring undefined throws a TypeError. Adding = {} after the pattern, as in function f({ a = 1 } = {}) {}, gives the parameter an object to destructure.