/ JAVASCRIPT

Object.is - An alternative to equality operators in JavaScript



JavaScript is a loosely typed language and in some cases it fall behind specially when it comes to equality comparision.

There are two operators to compare equality in JavaScript, double equal operator == and triple equal operator ===.

Comparing with double equal operator == gives unexpected results due to coercion or casting. It converts one of the two operands to the other operand’s type and then compare.

0 == ' ' //true
null == undefined //true
[1] == true //true

To avoid this situation, JavaScript provided the triple equal operator === which is more strict and does not coerce or cast operands, However comparing with triple equal operator === is still not the best solution.

NaN === NaN //false

Well, ES6 has another way of doing it. The new Object.is() which is better and more precise. It has the same features as triple equal operator === and moreover it behaves well in some special cases:

Object.is(0 , ' '); //false
Object.is(null, undefined); //false
Object.is([1], true); //false
Object.is(NaN, NaN); //true

Here is the comparision table among double equal operator ==, triple equal operator === and Object.is

X Y == === Object.is
undefined undefined true true true
null null true true true
true true true true true
false false true true true
‘codetonics’ ‘codetonics’ true true true
0 0 true true true
+0 -0 true true false
0 false true false false
’’ false true false false
’’ 0 true false false
‘0’ 0 true false false
‘99’ 99 true false false
[1,2] ‘1,2’ true false false
new String(‘codetonics’) ‘codetonics’ true false false
null undefined true false false
null false false false false
undefined false false false false
{name: ‘codetonics’} {name: ‘codetonics’} false false false
new String(‘codetonics’) new String(‘codetonics’) false false false
0 null false false false
0 NaN false false false
‘codetonics’ NaN false false false
NaN NaN false false true


Tagged In:  JAVASCRIPT,  OBJECT,  OPERATORS,  EQUALITY OPERATORS,  OBJECT.IS