Lodash _.isNaN() method
What you’ll learn
- How
_.isNaN(value)isolates numeric NaN without coercion traps. - Why lodash differs from legacy
isNaN(undefined)surprises. - How boxed
Number(NaN)objects behave versusNumber.isNaN. - When to pair NaN checks with
_.isFiniteor type guards.
Prerequisites
You know NaN is the only value where x !== x for primitives.
- You have seen global
isNaNcoerce operands before testing. - Try-it labs load lodash from the CDN.
Overview
Use _.isNaN when sanitizing math pipelines, parsed floats, or DOM-measured metrics—anywhere legacy isNaN might mislabel non-numbers.
Numeric gate
_.isNumber runs first—strings miss the NaN branch.
Boxed NaN
Object(NaN) unwraps via unary plus for detection.
No coercion
Avoids global isNaN truthy quirks on undefined.
Syntax
_.isNaN(value) - value: any value to test.
- Returns:
truewhen value is a numeric NaN (primitive or boxed); otherwisefalse.
Primitive and boxed NaN
Lodash matches the documented behavior for both forms.
import _isNaN from "lodash/isNaN";
console.log(
"nanPrim: " + _isNaN(NaN) + "\n" + // true
"boxedNaN: " + _isNaN(Object(NaN)) // true
); undefined: lodash vs global isNaN
Global isNaN coerces undefined to NaN; lodash rejects non-numbers first.
import _isNaN from "lodash/isNaN";
console.log(
"lodashUndef: " + _isNaN(undefined) + "\n" + // false
"globalUndef: " + globalThis.isNaN(undefined) // true
); Infinity and ordinary numbers
Non-NaN numeric values—including infinities—return false.
import _isNaN from "lodash/isNaN";
console.log(
"infinity: " + _isNaN(Infinity) + "\n" + // false
"fortyTwo: " + _isNaN(42) // false
); 📋 _.isNaN vs related checks
| API | Behavior |
|---|---|
_.isNaN(x) | true for primitive NaN and boxed Number(NaN); gated by _.isNumber. |
Number.isNaN(x) | true only for primitive NaN—boxed NaN objects return false. |
global isNaN(x) | Coerces with ToNumber; often true for undefined and "NaN". |
x !== x | Primitive NaN trick only—misses boxed NaN and reads oddly in reviews. |
Pitfalls to avoid
Strings before Number()
_.isNaN("NaN") is false—convert with Number() first if you intentionally parse.
Shadowing global
Importing as isNaN hides the built-in; alias like _isNaN when comparing behaviors.
Finite vs NaN
NaN is still a number type—pair with _.isFinite when rejecting non-usable math values.
❓ FAQ
Summary
- Purpose: detect numeric NaN without global coercion mistakes.
- Remember: non-numbers—including
undefined—exit asfalse. - Next: explore more on Lodash _.isNative().
_.isNaN implements _.isNumber(value) && value != +value—so only numeric NaN values qualify; undefined and strings return false, unlike global isNaN coercing them.
6 people found this page helpful
