Lodash defaultTo: Triggers for NaN Defaults
In the Lodash library, _.defaultTo is a utility method
designed to return a fallback value when an evaluated input resolves to
an invalid or unassigned state. This article explores the precise
conditions and parameter inputs that trigger default evaluation inside
_.defaultTo, with a particular focus on how JavaScript's
native NaN is strictly detected and handled alongside
null and undefined.
The _.defaultTo function takes two functional arguments:
value (the primary value to inspect) and
defaultValue (the fallback value returned if the evaluated
value is invalid).
Internally, Lodash evaluates whether to return
defaultValue using a strict, concise identity check:
return (value == null || value !== value) ? defaultValue : value;This logic dictates that exactly three native types of inputs
supplied to the primary value parameter will trigger the
execution branch for defaultValue:
NaNValues: In JavaScript,NaN(Not-a-Number) is the only value that is not equal to itself (NaN !== NaNevaluates totrue). Because Lodash testsvalue !== value, passingNaN,Number.NaN, or expressions that evaluate toNaN(such as0 / 0orparseInt('invalid')) as the first parameter strictly triggers the return ofdefaultValue.undefinedValues: Passing an explicitundefined, a void expression (void 0), or omitting the argument triggers thevalue == nullloose equality condition, automatically yieldingdefaultValue.nullValues: Passing an explicitnullalso satisfiesvalue == null, diverting the evaluation todefaultValue.
When defaultValue is explicitly set to NaN
(for example, _.defaultTo(value, NaN)), Lodash returns
NaN strictly when the value parameter is
null, undefined, or NaN.
Conversely, all other falsy JavaScript primitives—such as
false, 0, -0, 0n,
and empty strings ""—do not satisfy
(value == null || value !== value). When these values are
passed to the value parameter, _.defaultTo
strictly preserves and returns them, bypassing the
defaultValue fallback entirely.