Equality testing in JavaScript

Did you know that JavaScript has the “===” and “!==” operators to compare two variables?

When we have to check in JavaScript whether two variables are equal or not equal, we use “==” or “!=”. It’s just the habit of the C# programmer. But those two operators are not reliable. Why, you ask?

If the two values are of the same type, then it’s OK. Otherwise it forces a type coercion, meaning it tries to convert the two variables to the same type, in order for it to be able to compare them. This automatic forced conversion might be wrong, in which case your code will be wrong and the functionality you’ve implemented will be wrong.

The best way to check two values is to use the strict equal (“===”) and strict not equal (“!==”) operators. These operators verify if the two variables are of the same type AND if their values are equal/not equal.

If you want to read more about it, you could start with this: http://blog.boyet.com/blog/javascriptlessons/javascript-for-c-programmers-truth-and-falsity/

Regarding the equality operators, it writes:

JavaScript has the == operator, but in general you shouldn’t use it. A better equality comparison operator is the === operator (triple-equals), known as the identity operator.  Why?

The problem with the double-equals operator is that the interpreter will make great efforts to coerce the two values being compared into the same type so that they can then be compared. It’s a "lazy" comparison, not for the interpreter, but for the programmer. The triple-equals operator is much more rigorous — it checks the type to be equal too.

Let’s see some examples. If you run this set of statements in Firebug within Firefox, they’ll all print true:

 

   1: console.log(null == undefined)

   2: console.log("42" == 42)

   3: console.log('' == 0)

   4: console.log('0' == 0)

The rules for why these all evaluate as true are simple enough, but my recommendation is don’t rely on ==. For example, check out the last two statements. Since the empty string equals 0 and 0 equals the string ‘0’, then it must imply that ” == ‘0’. Sorry, nice try, but no it doesn’t. Since == can produce examples where the operator is not transitive, against all common logic, that’s a reason not to use it in my book. Stick to === and !==, that’s my advice.

This blog has a great number of useful JavaScript lessons which you should take a look at: http://blog.boyet.com/blog/javascriptlessons/

More explanations as to why === and !== is better, you can read here: http://msmvps.com/blogs/luisabreu/archive/2009/08/25/vs.aspx

Here’s another great post about other best practices in JavaScript: http://community.devexpress.com/blogs/ctodx/archive/2010/12/07/refactoring-javascript-to-follow-best-practices.aspx

Happy coding!