Lodash _.negate() method
What you’ll learn
- How
_.negateflips predicate truthiness. - How to reuse one predicate for both positive and inverted checks.
- How negate compares to manual boolean negation and
_.reject. - How to avoid confusion when predicates return non-boolean values.
Prerequisites
Helpful reads: _.memoize(), _.filter(), and the Function hub.
- Predicates: functions that return truthy/falsey outcomes.
- Collection methods: filtering and finding by predicate callbacks.
Overview
_.negate(predicate) returns a new predicate that yields true when the original returns falsey, and false when the original returns truthy.
Syntax
_.negate(predicate)- predicate: function whose result should be inverted.
- returns: wrapper predicate with opposite boolean outcome.
Invert an is-even predicate
Create isOdd from existing isEven without rewriting logic.
import negate from "lodash/negate";
const isEven = (n) => n % 2 === 0;
const isOdd = negate(isEven);
isOdd(3); // true
isOdd(4); // falseFilter items not matching a rule
Use one predicate for include and exclude flows by inverting it on demand.
import negate from "lodash/negate";
import filter from "lodash/filter";
const isActive = (item) => item.active === true;
const inactiveUsers = filter(
[{ id: 1, active: true }, { id: 2, active: false }],
negate(isActive)
);
// [{ id: 2, active: false }]Find first non-empty string
Invert an isEmptyString check to quickly locate valid values.
import negate from "lodash/negate";
const isEmptyString = (value) => value === "";
const isNonEmptyString = negate(isEmptyString);
["", "", "ready"].find(isNonEmptyString);
// "ready"📋 _.negate vs _.reject vs manual !
| Approach | Best for | Trade-off |
|---|---|---|
_.negate | Reusable inverted predicate functions | Extra wrapper function |
_.reject | One-off inverse filtering on collections | Tied to collection operation |
Manual ! | Inline quick checks | Less reusable and can get noisy in pipelines |
Pitfalls to avoid
Non-boolean predicate returns
Negate applies logical NOT to truthy/falsey values, so ensure predicate outputs are intentional.
Confusing double negatives
Prefer clear names like isNotArchived to avoid hard-to-read conditions.
Needless wrappers
For a single inline check, plain ! may be simpler than storing a new negated function.
❓ FAQ
Summary
- Purpose:
_.negateinverts predicate outcomes while preserving input forwarding. - Pattern: define one canonical predicate and derive inverse behavior from it.
- Next: Lodash _.once(), revisit Lodash _.memoize(), or read official _.negate docs.
Lodash _.negate(predicate) returns a wrapper that preserves incoming arguments and this, then flips the predicate result with logical NOT.
6 people found this page helpful
