What Values Does Lodash isNil Check For?
The _.isNil method in the Lodash JavaScript library is a
utility function designed specifically to determine whether a target
value is either null or undefined. This
article explains how the function evaluates these two specific values,
illustrates its behavior with practical examples, and clarifies how it
differs from other type-checking alternatives in JavaScript.
The Two Values Checked by _.isNil
In the Lodash library, _.isNil checks exclusively for
the following two values:
nullundefined
If the argument passed to _.isNil is either
null or undefined, the function returns
true. For any other value—including other falsy values such
as false, 0, "" (empty string),
or NaN—it returns false.
How It Works
Under the hood, _.isNil functions equivalently to the
loose equality check value == null. In standard JavaScript,
using the loose equality operator (==) against
null returns true only if the operand is
null or undefined.
Lodash wraps this check into a descriptive, readable utility function.
Code Examples
const _ = require('lodash');
// Returns true
_.isNil(null); // => true
_.isNil(undefined); // => true
_.isNil(void 0); // => true
// Returns false
_.isNil(false); // => false
_.isNil(0); // => false
_.isNil(''); // => false
_.isNil(NaN); // => false
_.isNil({}); // => false
_.isNil([]); // => falseDifference Between _.isNil, _.isNull, and _.isUndefined
Lodash provides individual checks for developers who need more strictness:
_.isNull(value): Returnstrueonly if the value is strictlynull._.isUndefined(value): Returnstrueonly if the value is strictlyundefined._.isNil(value): Combines the checks above, returningtruefor bothnullandundefined.
Summary
_.isNil is a nullish-checking utility that returns
true strictly for null and
undefined. It ensures that default values or guards are
applied appropriately without mistakenly catching valid falsy primitives
like zero or empty strings.