JavaScript

Use nullish coalescing for defaults

Use the nullish coalescing operator when a default should apply only to null or undefined. Unlike logical OR, it preserves intentional values such as zero, false, and an empty string.

Worked example

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

const settings = {retries: 0, enabled: false, label: ""};
console.log(settings.retries ?? 3);
console.log(settings.enabled ?? true);
console.log(settings.label ?? "Untitled");

How it works

The operator examines the left value without converting it to a boolean. This matters for retry counts, numeric form values, and flags where zero or false changes behavior deliberately. A missing retries property would receive the default three.

Limits and mistakes

Nullish defaults do not reject NaN or invalid strings. Validate those separately. Mixing nullish coalescing directly with logical AND or OR requires parentheses; make the intended grouping obvious to the next reader.

Check the result

Expect zero, false, and a blank line. Remove a setting and confirm only that setting falls back. Include null explicitly if the data source uses it for absence.

Sources

Reference documentation for the behavior used in this guide: