The Object.is()
method was introduced in ES6 (ECMAScript 2015) that can be used to determine whether two JavaScript objects or primitive values are equal.
Object.is()
is very similar to the JavaScript strict comparison operator ===
, but there are some slight differences which we'll cover in this article.
You can use Object.is()
with numbers, strings, and even objects to test equality as shown below:
Object.is('Mango', 'Mango'); // true
Object.is('Mango', 'Orange'); // false
Object.is(window, window); // true
Object.is(null, null); // true
Object.is([], []); // false
const animals = { penguin: '🐧' };
const fruits = { orange: '🍊' };
Object.is(animals, animals); // true
Object.is(animals, fruits); // false
// Special Cases
Object.is(-0, -0); // true
Object.is(0, -0); // false
Object.is(NaN, 0 / 0); // true
The Object.is()
method always returns false
unless one of the following conditions holds:
- Both values are
undefined
- Both values are
null
- Both values are either
true
orfalse
- Both values are strings of the same length with the same characters in the same order
- Both values are the same exact object (refer to the same object)
- Both values are numbers (and both
+0
, both-0
, or bothNaN
)
JavaScript treats +0
and -0
differently, so be careful when you're comparing them using Object.is()
.
Object.is()
vs. ===
Operator
Although Object.is()
and strict comparison operator(===
) can almost be used interchangeably, there are two main differences.
The first difference is that the ===
operator treats the number values -0
and +0
as equal which is not the case with Object.is()
:
-0 === +0; // true
Object.is(-0, +0); // false
The second difference is that the ===
operator, unlike Object.is()
, treats Number.NaN
as not equal to NaN
:
Number.NaN === NaN; // false
Object.is(Number.NaN, NaN); // true
Browser Compatibility
The Object.is()
method only works in modern browsers. If you need to support old browsers like Internet Explorer, use the following polyfill provided by MDN:
if (!Object.is) {
Object.defineProperty(Object, "is", {
value: function (x, y) {
// SameValue algorithm
if (x === y) { // Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
});
}
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.