DEV Community

Cover image for JavaScript comparison that never lies
Sergey Panarin
Sergey Panarin

Posted on

JavaScript comparison that never lies

Is there something not equal to itself?

One of the popular JavaScript questions among the interviewers:

Could x !== x?

It refers to one of the most unknown parts of JavaScript – types, coercion, and its corner cases.

In the example above for NaN even triple equal comparison lies. And is there some way to be sure what's inside the variable?

Function that never lies

Yes, there is – it's Object.is(x, y).

It tells the truth in all the cases, even for -0 or NaN.

// Object.is(x, y) never lies

console.log(Object.is(true,true) === true);
console.log(Object.is(false,false) === true);
console.log(Object.is(null,null) === true);
console.log(Object.is(undefined,undefined) === true);
console.log(Object.is(NaN,NaN) === true);
console.log(Object.is(-0,-0) === true);
console.log(Object.is(0,0) === true);
Enter fullscreen mode Exit fullscreen mode

Use it in your interview answers and in your code – Object.is never lies!

Top comments (0)