In ES6, what does 'Object.is()' do?

Understanding the 'Object.is()' Method in ES6

In ECMAScript 6 (ES6), the Object.is() method is introduced to perform a comparison between two values and determine if they are the same value. This method is different from the more familiar comparison operators (== and ===) in some critical aspects.

How Does 'Object.is()' Work?

The Object.is() method takes two arguments and checks if they are the same in terms of their value. Note, it's not about being the same object in memory (like comparing objects by reference), but about them having the same value. The syntax is quite straightforward:

Object.is(value1, value2);

This will return true if value1 and value2 are the same value, and false otherwise.

Practical Example

Let's take a look at a practical example to understand how it exactly works;

let x = { id: 1 };
let y = { id: 1 };
let z = x;

console.log(Object.is(x, y)); // false
console.log(Object.is(x, z)); // true

In the above example, even though x and y have the same value, Object.is(x, y) returned false because they are not the exact same object in memory. However, Object.is(x, z) returned true because z is pointing to the same object in memory as x.

Differences with Other Comparison Operators

The Object.is() method behaves differently than both the loose equality (==) and strict equality (===) operators in JavaScript in two specific cases—NaN and negative zero.

  • It considers NaN to be the same as NaN, while === considers NaN not to be the same as NaN.
  • It considers +0 and -0 as different values, while === and == consider them to be the same.

Here's an example demonstrating these differences:

console.log(Object.is(NaN, NaN)); // true
console.log(NaN === NaN); // false

console.log(Object.is(-0, +0)); // false
console.log(-0 === +0); // true

Overall, the Object.is() method provides us with an alternative way to compare values in JavaScript that can be more accurate in certain situations, especially when dealing with NaN and +0/-0.

Do you find this helpful?