Options objects: arguments by name

A function of four or five positional parameters is hard to call. The call site reads connect('example.com', 80, false, 1000) and nothing in it says which value is the host, which is the timeout, or what false switches off. The reader has to find the definition, and the writer has to count commas.

The usual answer in JavaScript is one object of named options. The caller writes the names, the order stops mattering, an option may be left out without disturbing the others, and a default in the parameter list covers the ones the caller did not mention. This lesson builds that style with destructuring, which the lesson on destructuring introduced.

The trouble with positional arguments

The function below takes four values in a fixed order. The first call is complete, the second forgets the timeout, and the third wants a timeout but does not want a secure connection, so it has to pass undefined to reach the fourth position.

function connect(host, port, secure, timeout) { return `${host}:${port} secure=${secure} timeout=${timeout}`; } console.log(connect('example.com', 80, false, 1000)); console.log(connect('example.com', 80, true)); console.log(connect('example.com', 80, undefined, 5000));

node positional.js

example.com:80 secure=false timeout=1000
example.com:80 secure=true timeout=undefined
example.com:80 secure=undefined timeout=5000

The third line is the cost of a positional list: to reach the timeout the caller had to count to the third position and write undefined there, which is a value nobody wants and every reader has to decode. The second line shows the other problem, an option that was simply forgotten and now appears in the output as the word undefined.

One object of options

The same function written with an options object takes the host first, because it is required, and one more parameter that is a destructuring pattern with defaults. The pattern names the options the function knows, gives each a default, and the = {} after it allows the caller to leave the whole object out.

function connect(host, { port = 80, secure = false } = {}) { return `${host}:${port} secure=${secure}`; } console.log(connect('example.com')); console.log(connect('example.com', { port: 8080 })); console.log(connect('example.com', { secure: true })); console.log(connect('example.com', { port: 8080, secure: true }));

node options.js

example.com:80 secure=false
example.com:8080 secure=false
example.com:80 secure=true
example.com:8080 secure=true

Every call says what it wants and nothing else: the second one changes the port and keeps the default of secure, the third does the opposite, and neither writes a placeholder for the other. The call site reads like a sentence, and the order of the two keys inside the object does not matter at all. This is the shape most of the standard library uses, from JSON.stringify to Intl.NumberFormat in the lesson on formatting.

Unknown keys and the rest of the options

A destructuring pattern reads only the keys it names, so an unknown key in the object is ignored without a word. That is convenient for callers and dangerous for typos: retires instead of retries is not an error, it is an option that quietly does nothing. A rest element in the pattern is the way to see the keys the function did not recognise.

function request(url, { method = 'GET', headers = {}, retries = 0 } = {}) { const names = Object.keys(headers); return `${method} ${url} headers=[${names.join(',')}] retries=${retries}`; } console.log(request('/users')); console.log(request('/users', { method: 'POST' })); console.log(request('/users', { retries: 2 })); console.log(request('/users', { method: 'POST', headers: { 'Content-Type': 'application/json' } })); function strict(url, { method = 'GET', ...others } = {}) { return `${method} ${url} unknown=[${Object.keys(others).join(',')}]`; } console.log(strict('/users', { method: 'POST', body: 'x', cache: false }));

node unknown.js

GET /users headers=[] retries=0
POST /users headers=[] retries=0
GET /users headers=[] retries=2
POST /users headers=[Content-Type] retries=0
POST /users unknown=[body,cache]

The second line changed the method and left the headers and the retries at their defaults, and the third changed the retries alone. The last line is the stricter version: the rest element collects body and cache, which the function does not handle, and a real function can throw or warn when that list is not empty instead of accepting a typo in silence. That rest element is the same three-dots syntax as the rest parameter of the previous lesson, applied to an object.

A required option

An options object with defaults describes the optional half of a call. The required half has to be checked, because a destructuring pattern with no default would fail with a message about the whole object rather than about the option. The usual pattern is a named parameter for the important value and a check in the body for an option that has no sensible default.

function save(record, { collection } = {}) { if (typeof collection !== 'string') { throw new TypeError('collection is required'); } return `${collection}/${record.id}`; } console.log(save({ id: 7 }, { collection: 'users' })); try { save({ id: 7 }); } catch (error) { console.log(error.name + ': ' + error.message); } const options = { port: 8080, secure: true }; const { port, secure } = options; console.log('destructured at the call site:', port, secure);

node required.js

users/7
TypeError: collection is required
destructured at the call site: 8080 true

The error names the option that is missing, which is what the caller needs, and the = {} means the failure is this message and not a crash inside the parameter list. The last lines show the other direction of the same syntax: the caller may keep its configuration in one object and destructure it into names before the call. An options object is a plain object, so it can be built by spreading a shared default and overriding a key or two, which is how a project keeps its connection settings in one place.

Exercises

  1. Call connect from options.js with an empty object. Which defaults apply, and what does the line print?
  2. Call connect with null instead of an object. What does the call throw, and which piece of the parameter list is missing?
  3. Add an option path with a default of '/' to request in unknown.js and include it in the returned text. Which calls change their output?
  4. Pass retires: 3 with a typo to strict in unknown.js. What does it report, and what would the non-strict version do?
  5. Build one options object from a shared default with the spread syntax and pass it to connect. Which value wins when the same key appears twice?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an options object replace in a long parameter list?

    Answer

    The order of positional arguments, with names

    Each value arrives under a name, so the caller writes what it means and the order stops mattering.

  2. What does the = {} after a destructuring pattern in the parameter list do?

    Answer

    It lets the caller leave the whole options object out

    Without it a call with one argument would destructure undefined and throw before the body runs.

  3. What does this program print? function f({ a = 1, b = 2 } = {}) { return a + b; } console.log(f({ b: 5 }));

    Answer

    6

    The object supplies b and the default supplies a, so the sum is 1 plus 5.

  4. What does this program print? function f(options = {}) { return options.a ?? "none"; } console.log(f());

    Answer

    none

    The default gives an empty object, its a is undefined, and the nullish operator then returns the text.

  5. What does this program print? function f({ a = 1 } = {}) { return a; } console.log(f({ a: 2, b: 3 }));

    Answer

    2

    The pattern reads a and ignores the key it does not name, so the extra option is silently dropped.

  6. What does this program print? function f({ a }) { return a; } try { f(); } catch (error) { console.log(error.name); }

    Answer

    TypeError

    Without the = {} the pattern destructures undefined, and reading a property of undefined is a TypeError.

  7. Why is an unknown key in an options object dangerous?

    Answer

    It is ignored, so a typo looks like an option that does nothing

    A destructuring pattern reads only the names it declares, so a misspelled key passes without a word unless the code collects the rest.

  8. What does a rest element in an options pattern collect?

    Answer

    The keys the pattern did not name

    The three dots gather everything that is left after the named keys were read, which is how a function can see unknown options.

  9. How does a function report an option that has no sensible default?

    Answer

    It checks the value and throws an error that names the option

    A check in the body gives a message the caller can act on, while a bare pattern fails with a message about the whole object.

  10. What does this program print? function f({ a = 1, ...others } = {}) { return a + ":" + Object.keys(others).join(","); } console.log(f({ a: 2, b: 3, c: 4 }));

    Answer

    2:b,c

    The pattern reads a and the rest element collects the two keys that are left, in the order they were written.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev