JavaScript gives us multiple ways to compare values: ==, ===, and Object.is.
Most of the time === is good enough, but it has some edge cases where results can be… surprising.
That’s where Object.is comes in.
📌 When was Object.is introduced?
- Introduced in ES6 (ECMAScript 2015).
- Designed as a more reliable equality check than
===.
🤔 Why do we need Object.is?
Strict equality (===) works in most cases, but fails in two tricky ones:
- NaN comparison
NaN === NaN // false ❌
Object.is(NaN, NaN); // true ✅
- +0 vs -0
+0 === -0 // true ❌
Object.is(+0, -0); // false ✅
So Object.is was introduced to fix these quirks and make equality checks more precise.
🔑 Comparing ==, ===, and Object.is
| Comparison |
== (loose) |
=== (strict) |
Object.is |
|---|---|---|---|
| Type coercion | ✅ Yes | ❌ No | ❌ No |
NaN === NaN |
false | false | ✅ true |
+0 === -0 |
true | true | ❌ false |
| Normal values | Works w/ coercion | Works strictly | Same as === (except above two cases) |
✅ Where should you use Object.is?
- Detecting NaN values
const value = 0 / 0; // NaN
console.log(Object.is(value, NaN)); // true
- Differentiating +0 and -0
console.log(Object.is(+0, -0)); // false
-
Shallow equality checks
Frameworks like React use
Object.isto compare props/state and avoid unnecessary updates.
🌍 Real-world usage
1. React state updates
React uses Object.is internally when checking if a new state value is different from the old one.
const [count, setCount] = useState(NaN);
// This won’t trigger a re-render
setCount(NaN); // Object.is(NaN, NaN) === true
If React only used ===, this would trigger a render unnecessarily.
2. React.memo shallow prop comparison
React.memo uses shallow equality with Object.is under the hood.
const MyComponent = React.memo(({ value }) => {
console.log("Rendered");
return <div>{value}</div>;
});
<MyComponent value={NaN} /> // Rendered
<MyComponent value={NaN} /> // Not rendered again ✅
This prevents wasted renders when props are effectively “the same.”
📝 Conclusion
Object.is is a small but powerful addition introduced in ES6. It behaves like === in most cases, but with two important differences:
- It considers
NaNequal toNaN. - It treats
+0and-0as different.
These differences make it a reliable choice for edge cases where strict equality falls short.
While you might not use it every day, it plays a crucial role in libraries like React, ensuring accurate comparisons and avoiding unnecessary work.
Top comments (0)