Lodash _.each Return False to Break Loop

In the Lodash JavaScript library, explicitly returning false from an iteratee function inside _.each (or its alias _.forEach) immediately halts the iteration and exits the loop early. This article covers how this early-exit mechanism operates, how it differs from returning other falsy values, and how it compares to native JavaScript iteration methods.

The Early-Exit Mechanism

When iterating through an array or object using _.each, Lodash evaluates the return value of the iteratee function on every cycle. If the function explicitly returns the boolean value false, the internal loop terminates immediately, preventing any remaining elements from being processed.

const _ = require('lodash');

const numbers = [1, 2, 3, 4, 5];

_.each(numbers, (num) => {
  if (num === 3) {
    return false; // Iteration stops here
  }
  console.log(num);
});

// Output:
// 1
// 2

In the example above, once the condition num === 3 is met, returning false acts identically to a break statement inside a traditional for loop. The values 4 and 5 are never evaluated.

Strict Requirement for the Boolean false

Lodash strictly checks for the primitive boolean value false. Returning any other falsy value—such as null, undefined, 0, "", or NaN—will not stop the iteration.

_.each([1, 2, 3], (num) => {
  return null; // The loop will continue running for all 3 items
});

_.each([1, 2, 3], (num) => {
  return 0; // The loop will continue running for all 3 items
});

A common standard return; statement within a function evaluates to undefined, which functions like a continue statement in a standard loop rather than a break.

Difference from Native Array.prototype.forEach

The behavior of _.each is a notable departure from native JavaScript's Array.prototype.forEach. The native ECMAScript implementation cannot be terminated early via a return statement; returning a value in a native forEach callback is simply discarded, and the loop always executes for every element.

Developers choosing between native arrays and Lodash often use Lodash's _.each specifically for this early termination feature without needing to write full for...of loops or rely on throwing exceptions.