defaultTo()
defaultTo<
T,D>(value,defaultValue):T|D
Returns the value if it's not null, undefined, or NaN; otherwise returns the default value.
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 |
|---|---|---|
1 | 1 | 1 |
null | default | default |
undefined | default | default |
NaN | NaN ![]() | 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

