I know that there are many quirks with the equality operator (==). For example, following are all true…
null == undefined
1 == '1'
true == 1
false == ''
In all the above cases, using identity operator (===) would have returned the (strictly) correct answer.
But, when I just want to compare simpler things that do not suffer from quirks, why shouldn’t I use the equality operator. For example…
typeof x == 'number'
str == 'something'
So, my question is; why does the equality operator have such a derogatory status, when in fact it’s useful in some situations.
There is absolutely nothing wrong with using
==when the operands are guaranteed to be of the same type. When the operands are of the same type, it is specified to perform exactly the same steps as===. A good example is when usingtypeof.The reason for
==being frowned upon in such circumstances is purely stylistic. The argument is that code is easier to read if===is used consistently throughout without having to consider the implications of seeing a use of==. A lot of this originates with Douglas Crockford and is perpetuated by his JSLint tool.