JavaScript

Use default function parameters predictably

Default parameters apply when an argument is omitted or explicitly undefined. They do not replace null, false, zero, or an empty string.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function label(value = "Untitled") { return value; }
console.log(label());
console.log(label(undefined));
console.log(label(null));
console.log(label(0));

How it works

The function signature documents the normal fallback at the call boundary. A default expression is evaluated when needed for that invocation. This differs from creating one mutable default object outside the function and sharing it among all calls.

Limits and mistakes

A default does not establish the argument’s type or validity. If null should also trigger the fallback, normalize with nullish coalescing inside the function. Avoid expensive or surprising side effects in default expressions that callers cannot easily see.

Check the result

Expect Untitled twice, then null and 0. Test all missing-value cases accepted by your API rather than assuming that an omitted argument and an explicitly null one are interchangeable.

Sources

Reference documentation for the behavior used in this guide: