The Object is() method

By

Learn how the JavaScript Object.is() method compares two values for equality, including how it treats NaN as equal and tells 0 apart from -0, unlike ===.

~~~

Object.is() compares two values and returns true if they are the same value. It was introduced in ES2015, and it works almost like ===, with two differences: it treats NaN as equal to itself, and it tells 0 apart from -0.

Usage:

Object.is(a, b)

The result is always false unless:

How is it different from ===?

For most values, the two behave the same:

Object.is('hello', 'hello') //true
Object.is(21, 21) //true
Object.is(null, undefined) //false

The first difference is NaN. In JavaScript, NaN === NaN is famously false. Object.is() fixes that:

NaN === NaN //false
Object.is(NaN, NaN) //true

This is the main reason to reach for Object.is(). Say you parsed some user input and want to know if the result is stuck at NaN. Comparing with === can never work, so before Object.is() you had to use Number.isNaN().

The second difference goes the other way. === considers 0 and -0 equal, while Object.is() does not:

0 === -0 //true
Object.is(0, -0) //false

0 and -0 are different values in JavaScript, so pay attention in this special case (convert all to +0 using the + unary operator before comparing, for example).

Where is it used in practice?

React uses this same-value comparison internally. When you call a state setter from useState(), React uses Object.is() to compare the new value with the old one, and skips the re-render if they match. Knowing how Object.is() behaves explains why setting state to the same string or number does nothing.

One pitfall

Object.is() is not a deep comparison. Two objects with identical content are still two different objects:

Object.is({ age: 36 }, { age: 36 }) //false

It only returns true for objects when both sides point to the same reference:

const flavio = { age: 36 }
Object.is(flavio, flavio) //true

If you need to compare object contents, compare the properties you care about one by one, or serialize both sides first. Object.is() won’t do it for you.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: