How is Object.is different from the === operator?
Object.is works like === with two differences: Object.is(NaN, NaN) is true, and Object.is(0, -0) is false. React uses it to compare state values.
Explain it simply
=== is the strict equality check most code uses. It has two odd corners:
NaN === NaNisfalse, even though both sides are the same thing.0 === -0istrue, even though JavaScript does keep a separate negative zero.
Object.is (ES6) fixes both corners. It is called "SameValue" equality. For everything else it behaves exactly like ===: no type conversion, and objects are compared by reference.
Negative zero is rare but real. For example, -5 * 0 produces -0, and 1 / -0 is -Infinity, so the sign can change later results.
Example
console.log(NaN === NaN); // Output: false
console.log(Object.is(NaN, NaN)); // Output: true
console.log(0 === -0); // Output: true
console.log(Object.is(0, -0)); // Output: false
console.log(Object.is("5", 5)); // Output: false
console.log(Object.is({}, {})); // Output: false
const a = { id: 1 };
const b = a;
console.log(Object.is(a, b)); // Output: trueWhat to say in the interview
"Object.is implements SameValue equality. It matches === except that NaN equals NaN and +0 doesn't equal -0. There's no coercion and objects are still compared by reference. React's useState and useEffect dependency checks use Object.is, which is why setting the same object reference doesn't trigger a re-render, while setting a new object with the same contents does."
Common mistakes
- Thinking
Object.isdoes a deep comparison of objects. It does not. - Using it everywhere instead of
===; it is only needed when NaN or -0 matter.