Lodash _.isNil() method
What you’ll learn
- How
_.isNil(value)spots exactlynullandundefined. - Why empty strings, numeric zero, and
falseare not considered nil. - How this differs from broad falsy checks and some TypeScript assumptions.
- Where nil guards fit in defensive defaults and API normalization.
Prerequisites
You know null is intentional absence while undefined often means “missing.”
- You have seen loose equality
value == nullused as an idiom. - Try-it labs load lodash from the CDN.
Overview
Use _.isNil before dereferencing optional props, merging configuration objects, or short-circuiting pipelines—without rejecting legitimate falsy business values.
Dual nullish
Single check covers both null and undefined.
Keeps 0 / \"\"
Falsy-but-valid inputs survive unlike naive if (!x) traps.
Readable guard
Pairs cleanly with lodash flows after _.get results.
Syntax
_.isNil(value) - value: any value to test.
- Returns:
truewhen value isnullorundefined; otherwisefalse.
null and undefined
Both literal forms register as nil—the lodash docs baseline.
import isNil from "lodash/isNil";
console.log(
"nullVal: " + isNil(null) + "\n" + // true
"undef: " + isNil(undefined) // true
); Falsy—but not nil—values
Numeric zero, empty strings, and NaN remain present values per lodash.
import isNil from "lodash/isNil";
console.log(
"zero: " + isNil(0) + "\n" + // false
"emptyStr: " + isNil("") + "\n" + // false
"nan: " + isNil(NaN) // false (lodash docs)
); void 0 and boolean false
void 0 evaluates to undefined; explicit false must stay usable.
import isNil from "lodash/isNil";
console.log(
"void0: " + isNil(void 0) + "\n" + // true
"falsePrim: " + isNil(false) // false
); 📋 _.isNil vs related checks
| API / pattern | Behavior |
|---|---|
_.isNil(x) | true only for null or undefined. |
x == null | Identical semantics—lodash wraps the idiom. |
x === undefined | Misses explicit null assignments. |
!x | Also catches 0, \"\", false, NaN. |
Pitfalls to avoid
|| pitfalls
value || fallback nukes valid 0; combine nil checks with nullish coalescing (??) when appropriate.
Sparse holes
Missing indices read as undefined yet behave subtly differently from explicitly stored undefined.
NaN discipline
Use _.isNaN when you specifically need numeric NaN detection.
❓ FAQ
Summary
- Purpose: recognize JavaScript nullish values without broader falsy coupling.
- Remember: implementation is
value == null. - Next: explore more on Lodash _.isNull().
_.isNil(value) is implemented as value == null, so both null and undefined match—the same idiom many teams use for optional guards.
6 people found this page helpful
