Lodash _.eq() method
What you’ll learn
- How
_.eq(value, other)performs a SameValueZero comparison. - Why
NaNcan matchNaNhere while===does not. - How
_.eqdiffers fromObject.isaround signed zeros. - Reference equality rules for objects and arrays.
Prerequisites
Comfort with ===, truthiness, and the idea that NaN !== NaN in JavaScript.
- You know primitives versus object references.
- You can open Try-it labs in the browser.
Overview
_.eq wraps SameValueZero semantics in one readable helper. Reach for it when you want predictable comparisons for tricky numeric edge cases without repeating boilerplate.
NaN-friendly
Compare computed floats without custom Number.isNaN branches everywhere.
Zeros aligned
SameValueZero treats 0 and -0 as equal.
Refs unchanged
Objects still compare by identity—deep equality belongs elsewhere.
Syntax
_.eq(value, other) - value: first value to compare.
- other: second value to compare.
- Returns:
trueif SameValueZero holds; otherwisefalse.
Primitives and strings
Same types and values compare as expected; mismatched types usually yield false.
import eq from "lodash/eq";
eq(42, 42); // true
eq("hi", "hi"); // true
eq(1, "1"); // false NaN and signed zero
SameValueZero fixes NaN comparisons and aligns 0 with -0.
import eq from "lodash/eq";
eq(NaN, NaN); // true (unlike NaN === NaN)
eq(0, -0); // true (Object.is disagrees here) Object identity
Two different object literals are not equal; only the same reference passes.
import eq from "lodash/eq";
var a = { x: 1 };
var b = { x: 1 };
eq(a, a); // true
eq(a, b); // false 📋 _.eq vs === vs Object.is
| API | NaN vs NaN | +0 vs -0 |
|---|---|---|
_.eq(a, b) (SameValueZero) | Equal | Equal |
a === b | Not equal | Equal |
Object.is(a, b) (SameValue) | Equal | Not equal |
Pitfalls to avoid
Expecting deep equality
Use _.isEqual or structured comparison utilities for matching object contents.
Loose == habits
_.eq does not coerce types like ==; 1 and "1" are not equal.
Need SameValue, not SameValueZero
If you must distinguish +0 and -0, prefer Object.is.
❓ FAQ
Summary
- Purpose: SameValueZero comparison in one call.
- Strength: sane rules for
NaNand signed zero. - Next: explore more on Lodash _.gt().
SameValueZero is the same rule used for Map and Set key equality: NaN matches NaN, and +0 matches -0.
6 people found this page helpful
