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

