Aller au contenu principal

defaultTo()

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

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

remarque

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