How Lodash _.isNull Strictly Checks for Null
This article explains how the _.isNull method in the
Lodash JavaScript library strictly evaluates null
assignments. It examines the underlying mechanism Lodash uses to confirm
the null primitive, highlights the common JavaScript quirks
surrounding null and undefined, and details
why using strict identity checks prevents unexpected type coercion in
your code.
The Mechanism Behind
_.isNull
At its core, Lodash implements _.isNull using
JavaScript's strict equality operator (===). In the Lodash
source code, the function is defined simply as:
function isNull(value) {
return value === null;
}By leveraging ===, Lodash guarantees that the operand
must match both the type and the exact primitive value of
null. It bypasses the type coercion that occurs with loose
equality operators, ensuring that only an explicit null
returns true.
Overcoming Native JavaScript Quirks
JavaScript handles null in ways that often confuse
developers relying on built-in operators like typeof or
loose equality (==):
- The
typeofBug: Runningtypeof nullreturns"object". This legacy bug from the initial version of JavaScript makestypeofuseless for validating whether a variable is strictlynull. - Loose Equality Coercion: Using
value == nullevaluates totrueif the variable is eithernullorundefined. While useful when checking for the absence of any value, it fails when a program must distinguish between an intentionally empty state (null) and an uninitialized state (undefined).
_.isNull eliminates these ambiguities by ensuring that
no coercion takes place.
Behavior Against Common JavaScript Values
To understand how strictly _.isNull behaves, consider
how it evaluates various falsy and non-null values:
_.isNull(null)returnstrue_.isNull(undefined)returnsfalse_.isNull(void 0)returnsfalse_.isNull(false)returnsfalse_.isNull(0)returnsfalse_.isNull('')returnsfalse_.isNull(NaN)returnsfalse_.isNull({})returnsfalse
Because strict equality requires identical memory references for objects or identical types and values for primitives, none of these values can trigger a false positive.
Practical Benefit in Application Logic
While writing value === null in native JavaScript
provides identical functionality, _.isNull offers
functional utility within Lodash's broader ecosystem. It can be passed
directly as a callback or predicate function to higher-order
functions—such as _.filter, _.reject, or
_.some—without the need to define an inline arrow
function:
// Using _.isNull as a predicate
const data = [1, null, 2, undefined, null, 3];
const nonNullValues = _.reject(data, _.isNull);
// Result: [1, 2, undefined, 3]Through this single, strict identity comparison, Lodash provides a predictable and declarative way to guard against incorrect variable states.