Skip to main content

Command Palette

Search for a command to run...

Why you should use Object.is() method for equality comparison

Object.is() vs ===

Published
โ€ข1 min read
Why you should use Object.is() method for equality comparison
S

I am Frontend developer with expertise in HTML , CSS and JavaScript . I have a very Good experience in developing websites using Angular framework , NgRx , RxJs .

My Goal on this platform is to support and help the frontend developers by sharing my knowledge and experience in frontend development.

The Object.is() method determines whether two values are the same value. The Object.is() behaves like === operator except it's behaviour with signed zeros and NaN.

Object.is() is better and precise than === strict equality operator. Object.is() useful in scenarios which includes working with NaN and signed zeroes.

Behaviour of Strict Equality Operator (===) with NaN

let amountA = NaN;
let amountB = NaN;
console.log(amountA === amountB); 
// Output
false

The strict equality considers NaN and NaN are different values. That is why it returns false.

Behaviour of Object.is() with NaN

let amountA = NaN;
let amountB = NaN;
console.log(Object.is(amountA, amountB)); 
// Output
true

Object.is() treats the NaN & NaN as same value. That is why it returns true.

Behaviour of Strict Equality Operator (===) with Signed Zeros

console.log(-0 === 0);     =>     true
console.log(+0 === -0);    =>     true
console.log(+0 === 0);     =>     true

Strict equality operator === treats +0 , -0 and 0 as same values.

Behaviour of Object.is() with Signed Zeros

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

But Object.is() treats the +0 & -0 as different values. But it treats +0 &0 as same values.

Please refer the Following Equality comparison table for reference : -

JavaScript-sameness-comparison-table (1).png