Why Use Lodash _.each Over Native forEach
While native JavaScript provides Array.prototype.forEach
for iterating over collections, Lodash's _.each (an alias
for _.forEach) offers enhanced flexibility, safety, and
functionality. This article explores why developers still rely on
Lodash's implementation, highlighting key advantages such as native
support for iterating over objects, the ability to exit loops early, and
robust defense against null or undefined values.
Seamless Support for Objects and Arrays
The native Array.prototype.forEach method functions
exclusively on arrays. To iterate over an object using vanilla
JavaScript, developers must first transform the object into an array
using Object.keys(), Object.values(), or
Object.entries().
In contrast, _.each natively accepts both arrays and
plain objects. When passed an object, it automatically traverses the
object's own enumerable string keyed properties, passing the value, key,
and the collection itself to the callback function:
const user = { name: 'Alice', role: 'Admin' };
// Iterates cleanly without Object.keys()
_.each(user, (value, key) => {
console.log(`${key}: ${value}`);
});Early Loop Termination
A well-known limitation of native forEach is that it
cannot be stopped or broken out of; it will execute the callback for
every single element unless an error is thrown.
Lodash solves this limitation by allowing early termination.
Returning false from the iteratee function immediately
exits the loop, functioning identically to a break
statement in a standard for loop:
_.each([1, 2, 3, 4, 5], (num) => {
if (num > 3) {
return false; // Stops execution immediately
}
console.log(num);
});Safe Handling of Null and Undefined
Attempting to run native forEach on a variable that
resolves to null or undefined results in an
uncaught
TypeError: Cannot read property 'forEach' of undefined. To
prevent application crashes, developers must write defensive checks or
use optional chaining (e.g., data?.forEach(...)).
Lodash’s _.each handles null,
undefined, and primitive values gracefully. If an invalid
collection is supplied, the method simply skips execution without
throwing a runtime error, reducing boilerplate validation code in
data-fetching pipelines.
Predictable Iteration Over Sparse Arrays
Sparse arrays—arrays with missing indices or empty slots—can
introduce subtle bugs in native iteration methods. Native
forEach skips empty slots entirely without invoking the
callback. Lodash standardizes iteration across different types of
array-like structures and sparse collections, ensuring that behavior
remains predictable across various JavaScript runtime environments.