In JavaScript there are two pairs of equality operators: ===
and !==
, and evil twins ==
and !=
(as described in JavaScript The Good Parts in> by Douglas Crockford).
===
and !==
The first pair of operators, ===
and !==
, works as ==
and !==
in most programming languages, if the values compared with ===
have the same value and are the same type true
is returned by the expression and if they are compared with !==
false
is returned.
Examples using ===
and !==
'' === '0' // false
0 === '' // false
0 === '0' // false
false === 'false' // false
false === '0' // false
false === undefined // false
false === null // false
null === undefined // false
' \t\r\n ' === 0 // false
==
and !=
The second pair of operators, ==
and !=
, works as follows, when both values are of the same type, the evil twins behave like the other pair of operators ( ===
and !==
), but when the values compared are of different types they try to correct the values by converting them, which seems cool, but can produce difficult results to understand and make it difficult to maintain the code.
Examples using ==
and !=
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
A recommendation given by Douglas Crockford is to never use the evil twins, instead of using ===
and !==
instead.