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:

  1. NaN Values: In JavaScript, NaN (Not-a-Number) is the only value that is not equal to itself (NaN !== NaN evaluates to true). Because Lodash tests value !== value, passing NaN, Number.NaN, or expressions that evaluate to NaN (such as 0 / 0 or parseInt('invalid')) as the first parameter strictly triggers the return of defaultValue.
  2. undefined Values: Passing an explicit undefined, a void expression (void 0), or omitting the argument triggers the value == null loose equality condition, automatically yielding defaultValue.
  3. null Values: Passing an explicit null also satisfies value == null, diverting the evaluation to defaultValue.

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.