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:

  1. It is not null or undefined.
  2. It is not a JavaScript Function.
  3. It has a valid length property.

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:

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:

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.