JavaScript quirks – equality operators and comparisons
JavaScript – developers either love it or hate it and it’s not that difficult to see why. It’s a slightly different way of thinking from C# or Java development. All of a sudden semi-colons are optional, variables are in global scope and your functions have become objects and not just methods in a Class.
When does 0 == “”?
One of the main differences between C# and Java, is that JavaScript features weak typing. This means that the equality operator coerced types to compare them. This can be a total nightmare for an inexperienced JavaScript developer as the “==” operator can yield some really peculiar results. For example:
"" == "0" // returns false 0 == "0" // returns true 0 == "" // returns true false == "false" // returns false false == "0" // returns true false == undefined // returns false false == null // returns false null == undefined // returns true " \t\r\n" == 0 // returns true
Interesting eh? So in JavaScript, the use of == is widely regarded as bad practice, and because of the coercion between its operands it has the potential to introduce bugs that will be frustrating to find. Luckily there is a better way…
The Strict Equality Operator
The strict equality operator is made up of three equals signs (===). It works a lot like the usual double equals (==) operator that we use in C# and Java, but in JavaScript it does not perform coercion between its operands. Now our equality comparisons perform as expected:
"" === "0" // returns false 0 === "" // returns false 0 === "0" // returns false false === "false" // returns false false === "0" // returns false false === undefined // returns false false === null // returns false null === undefined // returns false " \t\r\n" === 0 // returns false
In Summary
So as you can see from the examples above, it’s much safer to use the strict equality operator in your JavaScript code. Ultimately, it will cut accidental mistakes that are cause JavaScript’s types coercion. For more detailed explanation on this and some of the other quirks in JavaScript, check out JavaScript Garden as it really is a great resource.
Continue Reading