Skip to content
jshacks.dev
Functions

How to Write a Function That Accepts an Options Object With Defaults

Write a JavaScript function with an options object and defaults using destructuring, nested options, validation and TypeScript types. Node.js 24.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, Node.js, TypeScript and npm logos.

A function with five positional parameters is a puzzle at every call site: connect("db", 5432, true, false, 3000) tells nobody which true is which. An options object fixes that, connect({ host: "db", port: 5432, ssl: true, timeout: 3000 }), and lets you add a sixth option later without breaking any caller. The pattern is simple and has a few sharp edges: what happens when the argument is missing, when a value is undefined or null, when options are nested and when a caller misspells a key. This post builds a well-behaved options function on Node.js 24, step by step, with printed output for each edge. For a related look at the alternative, see making a function accept named arguments.

Destructuring with defaults

The shortest form puts the defaults in the parameter itself.

JavaScript
function connect({ host = "localhost", port = 5432, ssl = false } = {}) {
  return `${ssl ? "https" : "http"}://${host}:${port}`;
}

console.log(connect({ host: "db.example.com", ssl: true }));
console.log(connect({ port: 6000 }));
console.log(connect());
Text
https://db.example.com:5432
http://localhost:6000
http://localhost:5432

Two defaults work together here. Inside the braces, host = "localhost" supplies a default for each missing key. After the braces, = {} supplies a default for the whole argument, so connect() with nothing at all does not fail. Without that = {}, calling connect() would throw TypeError: Cannot destructure property 'host' of 'undefined' as it is undefined, because there is nothing to destructure. It is the most common mistake with this pattern.

What counts as missing

A default applies only when the value is undefined. It does not apply to null, 0, "" or false.

JavaScript
function show({ label = "none", count = 10 } = {}) {
  return `${label}/${count}`;
}

console.log(show({ label: undefined, count: undefined }));
console.log(show({ label: null, count: 0 }));
console.log(show({ label: "" }));
Text
none/10
null/0
/10

Passing undefined explicitly behaves like omitting the key, and anything else is a real value, even null and 0. That is usually what you want, since count: 0 is a meaningful request. It surprises people who expect null to fall back to the default. If you want that behavior, use ?? inside the function.

JavaScript
function show2(options = {}) {
  const label = options.label ?? "none";
  const count = options.count ?? 10;

  return `${label}/${count}`;
}

console.log(show2({ label: null, count: 0 }));
Text
none/0

The nullish operator ?? falls back for null and undefined but keeps 0. Do not use || here, since 0 || 10 is 10, and a caller who asked for zero would silently get ten.

Keeping the options object

Destructuring in the parameter list gives you the variables but throws away the object. Sometimes you need to pass the whole thing along, or detect which keys the caller set. Take the parameter whole and merge it with the defaults.

JavaScript
const DEFAULTS = { retries: 3, delayMs: 100, verbose: false };

function request(url, options = {}) {
  const settings = { ...DEFAULTS, ...options };

  return `${url} retries=${settings.retries} delay=${settings.delayMs}`;
}

console.log(request("/a"));
console.log(request("/b", { retries: 5 }));
console.log(request("/c", { delayMs: undefined }));
Text
/a retries=3 delay=100
/b retries=5 delay=100
/c retries=3 delay=undefined

Spreading merges all own enumerable keys, and later ones win, which is the right precedence. The third call shows a trap: { delayMs: undefined } overwrites the default with undefined, because the key exists. The destructuring form treats an explicit undefined as missing, and the spread form does not. If callers pass undefined on purpose, for example from optional values in their own code, filter such keys first.

JavaScript
function withoutUndefined(object) {
  return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
}

function request2(url, options = {}) {
  const settings = { ...DEFAULTS, ...withoutUndefined(options) };

  return `${url} delay=${settings.delayMs}`;
}

console.log(request2("/c", { delayMs: undefined }));
Text
/c delay=100

A separate defaults object also serves as documentation: one place lists every option and its default, which a reader can see without parsing the signature.

Required values and options together

A common signature mixes one required argument and an options object: request(url, options). Required values stay positional, because they are always there and usually obvious, and only the optional tuning goes into the object. If a function has several required values of the same type, such as copy(from, to), that is fine too, and a call like copy({ from, to }) is better only when the order is easy to confuse.

Nested options

Defaults for nested objects need care, because a shallow merge replaces the whole inner object.

JavaScript
const DEFAULT_CONFIG = { retry: { count: 3, delayMs: 100 }, timeoutMs: 5000 };

function configure(options = {}) {
  return { ...DEFAULT_CONFIG, ...options };
}

console.log(configure({ retry: { count: 5 } }));
Text
{ retry: { count: 5 }, timeoutMs: 5000 }

The caller changed only count, and delayMs disappeared, since the inner object was replaced. Merge the nested level explicitly.

JavaScript
function configure2(options = {}) {
  return {
    ...DEFAULT_CONFIG,
    ...options,
    retry: { ...DEFAULT_CONFIG.retry, ...options.retry },
  };
}

console.log(configure2({ retry: { count: 5 } }));
console.log(configure2());
Text
{ retry: { count: 5, delayMs: 100 }, timeoutMs: 5000 }
{ retry: { count: 3, delayMs: 100 }, timeoutMs: 5000 }

Spreading undefined, as options.retry is in the second call, is allowed and adds nothing, so there is no need to guard it. For more than one nested level, a general deep merge is the cleaner tool, and that has its own pitfalls, covered in implementing a deep merge.

Catching misspelled options

An options object has a weakness that positional parameters do not: a typo is silently ignored. connect({ hots: "db" }) runs happily with the default host. For a library, validating the keys is worth a few lines.

JavaScript
function connect2(options = {}) {
  const known = new Set(["host", "port", "ssl"]);
  const unknown = Object.keys(options).filter((key) => !known.has(key));

  if (unknown.length > 0) {
    throw new TypeError(`unknown option(s): ${unknown.join(", ")}`);
  }

  const { host = "localhost", port = 5432, ssl = false } = options;

  return `${host}:${port}:${ssl}`;
}

try {
  connect2({ hots: "db" });
} catch (error) {
  console.log(error.message);
}

console.log(connect2({ host: "db" }));
Text
unknown option(s): hots
db:5432:false

Throwing on unknown keys also surfaces options that were removed in a newer version, which is a useful signal. The cost is that passing an object with extra properties on purpose, such as one shared between several functions, now fails, so some APIs only warn.

Check the types of the values too. A port of "5432" as a string works until the code does arithmetic on it. Validate the values that matter, throw TypeError for the wrong type and RangeError for a number out of range, with the option name in the message.

TypeScript

In TypeScript, declare the options as an interface with every field optional, and give the parameter a default.

TypeScript
interface ConnectOptions {
  host?: string;
  port?: number;
  ssl?: boolean;
}

function connect({ host = "localhost", port = 5432, ssl = false }: ConnectOptions = {}): string {
  return `${ssl ? "https" : "http"}://${host}:${port}`;
}

The compiler now rejects connect({ hots: "db" }) as an excess property error for object literals, which gives you the typo check for free at compile time. The interface also gives editors something to complete, so callers see the available options as they type, which is the biggest practical benefit of the pattern.

Freezing and documenting the defaults

If the defaults live in a shared object, someone will eventually change it. A line such as DEFAULTS.retries = 10 in one module changes the behavior of every call in the program, which is a hard bug to trace. Freeze the defaults with Object.freeze so that an assignment fails, silently in sloppy mode and with a TypeError in modules and strict mode, and freeze nested objects too if you share them, since Object.freeze is shallow.

Document each option where it is declared: its type, its default and what it does. For a public function, that table is the real interface, and it belongs next to the code, not in a separate file that drifts. When you add an option later, give it a default that preserves the old behavior, and callers who never heard of it keep working. That compatibility is the reason the pattern exists.

When positional parameters are better

An options object is not always the right tool. One or two arguments whose meaning is obvious, such as add(a, b) or sleep(ms), are clearer positionally, and the object would add braces for no gain. Hot paths called millions of times may also prefer positional arguments, since creating an object per call costs an allocation. The rule of thumb: when there are more than three parameters, or several are booleans, switch to an options object.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("uses defaults when called with no arguments", () => {
  assert.equal(connect(), "http://localhost:5432");
});

test("an explicit undefined uses the default, null does not", () => {
  assert.equal(show({ label: undefined }), "none/10");
  assert.equal(show({ label: null }), "null/10");
});

test("nested defaults are merged", () => {
  assert.deepEqual(configure2({ retry: { count: 1 } }).retry, { count: 1, delayMs: 100 });
});

test("unknown options are rejected", () => {
  assert.throws(() => connect2({ nope: 1 }), TypeError);
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0
Taggedbeginner
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.