Lodash overEvery Boolean Reduction Explained
The _.overEvery function in the Lodash JavaScript
library creates a composite function that evaluates a collection of
predicate functions against provided arguments, combining the individual
results using a logical AND reduction. This article explores how
_.overEvery functions, its short-circuiting behavior, and
how it implements this specific boolean reduction pattern in JavaScript
applications.
The Logical AND Reduction
In boolean logic, combining multiple conditional checks where all
must evaluate to truthy values is a conjunction, commonly known as a
logical AND (&&) reduction. In functional
programming, this corresponds directly to the universal quantifier, or
the standard every operation found on JavaScript
arrays.
When you pass an array of predicate functions to
_.overEvery, Lodash produces a new function. When this
generated function is invoked with arguments, it applies those arguments
to each predicate in sequence and reduces the collection of return
values down to a single boolean:
- If all predicates return a truthy value, the
overall expression evaluates to
true. - If any predicate returns a falsy value, the overall
expression evaluates to
false.
Short-Circuit Evaluation
Like the native JavaScript && operator and
Array.prototype.every(), Lodash's _.overEvery
applies short-circuit evaluation.
The predicates are invoked in the order they appear in the array. If a predicate evaluates to a falsy value, execution stops immediately, and the remaining predicates in the list are never called. This prevents unnecessary computation and prevents side effects from subsequent functions once failure is guaranteed.
Code Demonstration
Consider the following implementation showing the logical AND behavior:
const _ = require('lodash');
const isEven = (n) => n % 2 === 0;
const isPositive = (n) => n > 0;
const isUnderTen = (n) => n < 10;
// Creates a composite predicate combining all three via logical AND
const isValidNumber = _.overEvery([isEven, isPositive, isUnderTen]);
console.log(isValidNumber(4)); // true (even, positive, and < 10)
console.log(isValidNumber(-2)); // false (fails isPositive; isUnderTen is never executed)
console.log(isValidNumber(12)); // false (fails isUnderTen)In summary, _.overEvery reduces an arbitrary list of
predicates down to a single logical conjunction
(Predicate1 && Predicate2 && ... && PredicateN),
offering a declarative and reusable alternative to chaining native
logical operators.