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 crossdefault checkmark

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 results could be NaN.

defaultTo(part / total * 100, 0); // => 0 when total is 0
defaultTo(sum / nums.length, 0); // => 0 for empty array

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