How Lodash _.reject Coerces Truthy Values

This article examines how the Lodash library's _.reject method handles predicate evaluations, detailing the specific logical coercion applied to filter out truthy values. By understanding JavaScript's implicit boolean coercion and Lodash's internal rejection mechanism, developers can predict exactly how custom or default predicates determine which collection elements are discarded.

Understanding _.reject in Lodash

The _.reject method is the inverse of _.filter. It iterates over an array or object collection and returns a new array containing only the elements for which the predicate function does not return a truthy value. If the predicate returns a truthy value for an item, that item is excluded from the final output.

The Logical Coercion Mechanism

Lodash evaluates predicate outcomes using JavaScript's native abstract operation ToBoolean via logical negation (!).

Internally, _.reject wraps or complements the predicate using a negation pattern equivalent to:

!predicate(value, index, collection)

Because of this logical NOT (!) operation, the return value of the predicate undergoes standard ECMAScript boolean coercion:

  1. Evaluation: The predicate function runs and returns an arbitrary value (e.g., an object, number, string, or boolean).
  2. Boolean Conversion (ToBoolean): JavaScript checks whether the returned value belongs to the set of falsy values (false, 0, -0, 0n, "", null, undefined, and NaN). Any value outside this set is deemed "truthy."
  3. Inversion: A truthy value coerces to true in a boolean context. The logical NOT operator immediately converts true to false.
  4. Exclusion: Because the inverted result is false, the element fails the collection condition and is omitted from the resulting array.

Truthy Values and Shorthand Predicates

The type of coercion applied also depends on how the predicate is passed to _.reject:

Summary

The logical coercion applied to values filtered out by Lodash's _.reject is standard JavaScript ToBoolean coercion mediated by logical inversion (!). Any return value from the predicate that does not strictly resolve to a specification-defined falsy value is coerced to true, inverted to false, and rejected from the final collection.