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:
- Evaluation: The predicate function runs and returns an arbitrary value (e.g., an object, number, string, or boolean).
- Boolean Conversion (
ToBoolean): JavaScript checks whether the returned value belongs to the set of falsy values (false,0,-0,0n,"",null,undefined, andNaN). Any value outside this set is deemed "truthy." - Inversion: A truthy value coerces to
truein a boolean context. The logical NOT operator immediately convertstruetofalse. - 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:
- Custom Function Predicate: If a function returns an
object (
{}), a non-empty string ("hello"), or a number other than zero (1), these values are coerced totrue, causing the item to be rejected. - Property Name Shorthand (
_.property): When passing a property string (e.g.,_.reject(users, 'active')), Lodash resolves the value of that property on each item and evaluates its truthiness. Ifuser.activecontains any truthy value, it coerces totrueand is filtered out. - Matches Property Shorthand (
_.matchesProperty) and Identity: When using shorthands like['active', true], the helper returns a strict boolean (trueorfalse), which is then inverted.
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.