develwithoutacause, #JavaScript #CodeReview: Always use
===
over==
.
===
applies much more reasonable behavior for operands of different types, mainly by not coercing them together like==
does.A lot of developers will tell you to learn the rules of coercion and use it when appropriate, however I disagree for one key reason. Consider this example:
if (foo == bar) { doSomething(); }
Question: Did the developer mean to use
==
? Is the coercion intended or a typo?It's incredibly difficult to know with any amount of certainty as this depends on the types and semantics of
foo
andbar
.If I was writing this intentionally, I would feel compelled to write a several line comment about how coercion behavior applies here in a desirable way. And if you need to write that much explanation, it would be much less confusing to actually codify the desired behavior with
===
and explicit type checks so devs don't have to understand that coercion.