JavaScript has === and you should use it!!!

In javascript, there are two distinct sets of comparison operators. They provide very different and unexpected results. Using the wrong comparisons can produce very obscure and hard to trace bugs.

The first set are == and != that most programmers are familiar with. These look exactly like other languages.

The second set are === and !== that most programmers are not familiar with. These look bizarre when you’re used to other languages.

The double equals does a type conversion before the comparison. This can produce unexpected behavior than the programmer’s intention. Triple equals does comparison without the type conversion so this is a much safer and correct comparison.

The following table lists some of the quirks around this issue. It’s not a comprehensive list by any means, just a sampling. You can click all the links under “prove it” to try it out for yourself.

javascript expression prove it IE 6 result Firefox 3 result Chrome result
0 == false; “0 == false” true true true
0 === false; “0 === false” false false false
“” == false; “” == false true true true
“” === false; “” === false false false false
null == undefined; null == undefined true true true
null === undefined; null === undefined false false false
0 == ‘0’; “0 == ‘0’” true true true
0 === ‘0’; “0 === ‘0’” false false false

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply