Passing Non-Arrays to Lodash Array Methods

When non-array values are passed to array methods in the Lodash JavaScript library, the functions fail safely instead of throwing runtime exceptions. Unlike native JavaScript array methods that throw errors when operating on incompatible types, Lodash employs defensive type-checking to return fallback values—typically an empty array, undefined, or the unmodified input—depending on the specific method and argument provided.

Safe Fallbacks for null and undefined

In standard JavaScript, calling an array method on null or undefined results in a TypeError. Lodash methods guard against these values internally. When an array method receives null or undefined, it safely resolves to a default output:

// Native JavaScript throws:
// null.slice(1); // TypeError: Cannot read properties of null

// Lodash fails safely:
_.drop(null, 2); // Returns []
_.head(undefined); // Returns undefined

Handling Primitives (Numbers and Booleans)

Primitive types like numbers, booleans, and symbols do not have array-like structures. When passed into Lodash array methods, Lodash checks if the value can be converted or indexed. Because these primitives lack an iterable structure and a valid length property, Lodash treats them as empty:

Handling Array-Like Values and Strings

Lodash distinguishes between purely non-array values and "array-like" values (objects containing a numeric length property, such as strings, the arguments object, or custom DOM collections).

For methods specifically categorized under Lodash’s Array module:

Benefits and Trade-Offs

The primary benefit of Lodash's handling of non-array inputs is application resilience. UI components and data-processing pipelines do not crash unexpectedly when processing uninitialized or malformed API responses.

The trade-off is the potential masking of logical bugs. Because Lodash handles invalid types silently, passing an incorrect data structure may not generate an immediate error, causing failures further down the execution pipeline when an empty array or undefined is not explicitly anticipated.