Lodash _.every Return Value for Empty Collections

This article examines the return behavior of the _.every method in the Lodash JavaScript utility library when it evaluates an empty collection. While evaluating empty data sets can sometimes yield unexpected results in programming, understanding this specific behavior clarifies how JavaScript and Lodash handle conditional checks across arrays and objects.

In the Lodash library, the _.every method returns true when called on an empty collection, regardless of the predicate function passed to it.

const _ = require('lodash');

console.log(_.every([], Boolean)); 
// Output: true

console.log(_.every({}, () => false)); 
// Output: true

Why Does It Return True?

The return value of true is based on the mathematical and logical concept known as vacuous truth.

The definition of _.every states that the function returns true if the predicate returns truthy for all elements of the collection. Because an empty collection contains zero elements, there are no elements present that can fail the test or return a falsy value. Since no element violates the condition, the criteria for "all elements passing" is satisfied by default.

Alignment with Native JavaScript

Lodash’s implementation directly mirrors the behavior of ECMAScript’s built-in Array.prototype.every() method. In native JavaScript, executing [].every(fn) also immediately returns true without ever executing the callback function.

Practical Considerations for Developers

Relying on _.every without checking the collection size can introduce logic bugs if your application logic assumes that an empty collection should not pass validation.

If your application requires that a collection is both non-empty and that every element matches a specific condition, you should explicitly check the collection's length or size:

const isValid = collection.length > 0 && _.every(collection, predicate);

By adding an explicit check for the collection's presence and length, you ensure that empty inputs do not unintentionally pass through your validation steps.