How to avoid automatic type conversion in JavaScript
A very common problem when people code JavaScript, is that they don’t take automatic type conversion into account. As a result, there are numerous weird errors and JavaScript is getting a lot of blame for being loosely typed. Therefore, I’d like to show you an easy way to avoid that problem.
Most people write comparison checks just like they would in any other language. E.g:
if (valueOne == valueTwo)
The thing with JavaScript, though, is that if the values are of different types but seem to consist of the same value, a conversion is taking place, changing the type of one or several of the values. For instance, this equals true:
5 == "5"
The reason is that the values are converted into the same type, and then compared, hence the result becomes true. Also, this goes for all different types in JavaScript. A good way to make this never happen is to use type and value checking, like this:
5 === "5"
or this:
5 !== "5"
By using three equal signs or one exclamation sign and two equal signs, it also makes sure to compare if the values are of the same type or not, i.e. both being numbers, strings etc. This is also a practice recommended when working with JSLInt.
So, from now, don’t forget the type checking availability in JavaScript!


