How Lodash isArrayLike Checks Iterability
In Lodash, the _.isArrayLike method provides a reliable
way to determine if a value can be treated as an array without requiring
it to be an actual Array instance. This article explores
the internal mechanics of _.isArrayLike, breaking down the
specific criteria Lodash uses—namely non-null checks, function
exclusion, and length validation—to decide whether a value has an
indexed structure suitable for iteration.
The Core Verification Logic
Lodash determines if an item is "array-like" by evaluating three fundamental conditions directly in its source code. An item is considered array-like if:
- It is not
nullorundefined. - It is not a JavaScript
Function. - It has a valid
lengthproperty.
In the Lodash implementation, the function is concise:
function isArrayLike(value) {
return value != null && typeof value !== 'function' && isLength(value.length);
}Validating the
Length Property with isLength
The heavy lifting of the validation relies on the internal
isLength helper. For a length property to be
valid, it must meet strict numeric boundaries:
- Type Check: The
lengthmust be a standard JavaScriptnumber. - Non-Negative Integer: The value must be greater
than or equal to
0and have no fractional component (length % 1 === 0). - Safe Integer Constraint: The length cannot exceed
Number.MAX_SAFE_INTEGER(9007199254740991).
If an object possesses a length property that matches
these conditions, Lodash assumes the object uses numeric indices
corresponding to its length.
Why Functions Are Excluded
In JavaScript, functions naturally have a .length
property that indicates the number of arguments expected by the function
(arity). Because functions have a valid numeric length, naive checks
would classify them as array-like. Lodash explicitly checks
typeof value !== 'function' to prevent functions from being
mistakenly treated as iterable collections.
Values That Pass the
_.isArrayLike Check
A value does not need to be an actual Array to pass this
test. Common data structures that evaluate to true
include:
- Standard JavaScript arrays (
[1, 2, 3]) - Strings (
'hello'), which have a numeric length and indexed character access - The
argumentsobject inside standard functions - Browser collections, such as
NodeListorHTMLCollection - Custom plain objects with a valid length property (e.g.,
{ length: 2, 0: 'a', 1: 'b' })
Array-Like vs. ES6 Iterables
It is important to distinguish between an "array-like" object and an ES6 "iterable."
_.isArrayLike checks strictly for indexed iteration via
a numeric length property. It does not check for the presence of
Symbol.iterator. Consequently, structures like
Map and Set evaluate to false
under _.isArrayLike because they rely on internal size
mechanisms and iterator protocols rather than an exposed
.length property. Lodash uses this specific definition so
that utilities like _.forEach can safely iterate over the
target using standard, zero-based indexed loops.