JavaScript Object.is() method to check equality of two values

The Object.is() method checks if two values are the same value and returns a boolean value indicating the same. Syntax is:

Object.is(value1, value2);

This method doesn’t perform type conversion while comparing the values. Therefore, it returns false if both the values are of different types.

Object.is(10, 10); // true
Object.is(10, '10'); // false
Object.is(true, false); // false
Object.is(5 > 2, true); // true
Object.is('Hi', 'Hi'); // true
Object.is('bye', 'BYE'); // false
Object.is('Hi', 'Hello'); // false
Object.is([], []); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(undefined, null); // false

const x = 50;
Object.is(x, 50); // true

const ob = { x: 5 };
const ob2 = ob;
Object.is(ob, ob2); // true
Object.is(ob, { x: 5 }); // false

This method compares all values in a similar way to === except for signed zeros (+0, -0) and NaN values. The === operator treats signed zeros as the same and NaN values as different, whereas Object.is() treats signed zeros as different and NaN values as the same.

// using Object.is() method
console.log(Object.is(+0, -0)); // false
console.log(Object.is(0, 0)); // true
console.log(Object.is(NaN, NaN)); // true

// using === operator
console.log(+0 === -0); // true
console.log(0 === 0); // true
console.log(NaN === NaN); // false

See Next

Leave a Reply

Your email address will not be published. Required fields are marked *