Object.is() provides a true comparison for any object. Start using it today if you have missed out so far..!
Consider the code below -
console.log("abc" == "abc"); // true
console.log(null == null); // true
console.log(1 == 1); // true
// break
console.log(0 == false); // true
console.log("" == false); // true
While we are ok with the statements above break, the statements below can cause a problem.
Typically this is overcome by using strict comparison -
console.log("abc" === "abc"); // true
console.log(null === null); // true
console.log(1 === 1); // true
console.log(0 === false); // false
console.log("" === false); // false
But, what about the only edge case that is so.. so.. so important -
console.log(NaN == NaN); // false
console.log(0 === -0); // true
Will you use ==, ===, invent your own ====, or just get flustered enough to ignore the edges?
Now* you may not do any of those things. Object.is() is here.
Object.is() not only solves the most common equality problems..
console.log(Object.is(null, null)); // true
console.log(Object.is(1, 1)); // true
console.log(Object.is("abc", "abc")); // true
But also, solves the ‘super important’, ‘most commonly used’ edge cases.
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0, -0)); // false
Simply do Object.is everywhere and sleep peacefully at night..
Or.. no. Hold on a minute - how about those pesky objects?
console.log(Object.is({ name: "apple" }, { name: "apple" })); // false
console.log(Object.is([1, 2, 3], [1, 2, 3])); // false
Objects still work on the same principle - you need to manually compare values. Object.is() cannot convert the reference properties of an object magically. Give it a break, y’all.
* now = circa ES6. I am late to the party, can’t keep track of everything now.