Skip to main content

defaultTo()

defaultTo<T, D>(value, defaultValue): T | D

Returns the value if it's not null, undefined, or NaN; otherwise returns the default value.

note

Unlike ?? (nullish coalescing), this also handles NaN.


Type Parameters​

T: T​

The type of the value.

D: D​

The type of the default value.


Parameters​

value: T | null | undefined​

The value to check.

defaultValue: D​

The default value.


Returns: T | D​

The value if valid, otherwise the default value.


Since​

2.0.0


Also known as​

defaultTo (Lodash, es-toolkit, Remeda, Ramda) · getOrElse (Effect) · ❌ (Radashi, Modern Dash, Antfu)


Example​

defaultTo(1, 10);         // => 1
defaultTo(undefined, 10); // => 10
defaultTo(null, 10); // => 10
defaultTo(NaN, 10); // => 10

// Compare with ?? operator
NaN ?? 10; // => NaN
defaultTo(NaN, 10); // => 10

// Type narrowing
const value: string | undefined = getValue();
const result = defaultTo(value, 'default'); // => string

How it works?​

Returns the value if valid, otherwise returns the default value. Unlike ??, also handles NaN.

Comparison with ??​

Value??defaultTo
111
nulldefaultdefault
undefineddefaultdefault
NaNNaN default

NaN Handling​

Use Case​


Use Cases​

Handle NaN from calculations πŸ“Œβ€‹

Provide fallback values when calculations might produce NaN. Unlike ??, handles NaN which is a common edge case.

defaultTo(parseInt('invalid'), 0); // => 0 (NaN falls back)
parseInt('invalid') ?? 0; // => NaN (?? doesn't handle NaN)

Safe division with fallback πŸ“Œβ€‹

Handle division edge cases where both operands are zero (0/0 = NaN).

defaultTo(0 / 0, 0);             // => 0 (NaN falls back)
defaultTo(sum / nums.length, 0); // => 0 for empty array (0/0 = NaN)

Resolve text direction with fallback​

Resolve the document direction with a fallback when the attribute is missing. Essential for bidirectional text support in design systems.

const getDirection = (element: HTMLElement) =>
defaultTo(element.getAttribute("dir"), "ltr");

// Returns "rtl" if set, "ltr" as fallback
const dir = getDirection(document.documentElement);
applyDirectionalStyles(dir);

Fallback overlay z-index when not specified​

Provide a default z-index for overlays when none is configured. Perfect for overlay systems with optional z-index configuration.

const overlayZIndex = defaultTo(config.zIndex, 1000);
overlay.style.zIndex = String(overlayZIndex);

Config value resolution with nullish fallback​

Resolve configuration values handling null, undefined, and NaN.

defaultTo(config.timeout, 5000);   // => 5000 if undefined
defaultTo(config.threshold, 0.5); // => 0.5 if NaN