Why Lodash isEmpty Returns True for Integers
In JavaScript, developers often expect Lodash's
_.isEmpty function to return false for
numbers, assuming that a value like 42 or even
0 represents an existing, non-empty data point. However,
_.isEmpty evaluates integers—and all other primitive
numbers—as true. This article explains the internal
mechanics of _.isEmpty, why numbers are treated as empty,
and the proper alternatives to use when validating numeric values.
The Purpose of
_.isEmpty
Lodash's _.isEmpty is specifically designed to check the
emptiness of collections, not primitive values. It checks whether an
enumerable collection (like an Array, Object, Map, or Set) or a sequence
(like a String) has any elements or length.
According to Lodash’s documentation, a value is considered empty if it is an empty array, string, arguments object, map, set, or an object with no enumerable string keyed properties.
Why Integers Return
true
Under the hood, _.isEmpty executes checks in a specific
order:
- Nullish check: If the value is
nullorundefined, it returnstrue. - Array-like check: It checks if the value has a
valid numeric
lengthproperty (such as arrays, strings, or NodeLists). Numbers do not have alengthproperty. - Map and Set check: It checks if the value has a
.sizeproperty. Numbers do not have asizeproperty. - Object check: It checks whether the value is an
object with enumerable own properties using
Object.keys()or a similar internal method.
Primitive numbers have no length, no size, and no own enumerable properties. For example:
Object.keys(42); // returns []Because Object.keys(42) produces an empty list, Lodash
sees zero enumerable keys. As a result, Lodash’s fallback mechanism
considers the value to have no contents and returns
true.
Common Misconception: Truthiness vs. Emptiness
A frequent source of confusion is conflating JavaScript truthiness with collection emptiness. In standard JavaScript:
Boolean(42)evaluates totrue.Boolean(0)evaluates tofalse.
However, _.isEmpty(42) and _.isEmpty(0)
both evaluate to true because _.isEmpty does
not measure truthiness. It strictly evaluates whether a data container
contains items. Numbers are atomic values rather than containers.
How to Correctly Check Numbers
If you need to validate whether an integer or number exists and
contains a valid value, avoid _.isEmpty. Instead, use
native JavaScript checks or specialized Lodash utilities:
To check if a value is a valid number:
typeof value === 'number' && !Number.isNaN(value); // Or using Lodash: _.isNumber(value) && !_.isNaN(value);To check if a value is not
nullorundefined(including0):value !== null && value !== undefined; // Or using Lodash: !_.isNil(value);To check for finite integers:
Number.isInteger(value); // Or using Lodash: _.isInteger(value);
Using the appropriate type-checking function ensures your application
handles numeric inputs accurately without falling into the
container-based logic of _.isEmpty.