Learning to love “==”

the myth of avoiding type coercion in JavaScript


Many JavaScript developers and a lot of style guides will tell you to avoid “==” in your code. And there’s good reason for that advice. “==” can lead to some crazy and unpredictable results.

For example:

0 == “0" // returns true

0 == [ ] // returns true

“0" == [ ] // returns false ??? wtf??

For a through look at JavaScript quirks see wtfJS.

The reason for this craziness is type coercion. Unlike “===”’ insistence on strict equality, “==” will try to convert the things on each side of the operator to be the same type. The rules for type coercion can be a little bit tricky and unless you know them well you may run into edge cases like the ones above. So, the common advice goes, avoid “==” and its type coercing ways at all costs.

But it turns out that running away from “==” doesn’t solve your problem. Double equals is just one of many many places in JavaScript where type coercion occurs.

For example:

“a”+ 5 // Returns “a5” because 5 is coerced into a string

or

var x;

if (x) { doSomething( );} // runs the doSomething function because x gets coerced into true or false.

There is a long list of JavaScript functions that use type coercion including most basic math operators and truth tests and really almost any method that exists for two types of objects (e.g. concat works with both arrays and strings).

Not only is this behavior pervasive in JavaScript, it’s well supported. Every browser supports type coercion going back many generations. And the spec for ECMAScript 5 actually expanded type coercion rather. It’s clearly not going away.

So if we can’t avoid type coercion, we have no choice but to embrace it. As a community of JavaScript developers, we should review the rules and learn to love them. An excellent summary of the mechanics of type coercion can be found here.

A final type coercion fun fact- there is a slight performance hit on any function which has type coercion since at the very least it adds an additional type check to the function. That means that 5 == 5 is slightly slower than 5 === 5.

Craziness.

Email me when Kyle Warneck publishes or recommends stories