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.
It is considered bad because of something called type coercion.
It means that "" == false is true in JavaScript, but "" === false is not.
That might be what you want, but might not be.
Saying this is ALWAYS bad practice is too much of a sweeping statement. It is bad if you don't know what it does and means.
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 using typeof.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With