DEV Community

Vishwark
Vishwark

Posted on

Object.is in JavaScript ⚑ The Equality Check Nobody Talks About 🀯

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:

  1. NaN comparison
NaN === NaN      // false ❌
Object.is(NaN, NaN); // true βœ…
Enter fullscreen mode Exit fullscreen mode
  1. +0 vs -0
+0 === -0        // true ❌
Object.is(+0, -0); // false βœ…
Enter fullscreen mode Exit fullscreen mode

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?

  1. Detecting NaN values
const value = 0 / 0; // NaN
console.log(Object.is(value, NaN)); // true
Enter fullscreen mode Exit fullscreen mode
  1. Differentiating +0 and -0
console.log(Object.is(+0, -0)); // false
Enter fullscreen mode Exit fullscreen mode
  1. Shallow equality checks Frameworks like React use Object.is to 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
Enter fullscreen mode Exit fullscreen mode

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 βœ…
Enter fullscreen mode Exit fullscreen mode

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 NaN equal to NaN.
  • It treats +0 and -0 as 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)