Before we begin our JS Coercion exploration it’s worthy to note that this post exists because JS is an untyped language(maybe weakly-typed based upon your definition).
A strongly-typed programming language is one in which each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.
What this means for us as JS users is that the language may be forced to make certain rule based Type decisions at compile time. In this post we will refer to 2 different types of coercion, Explicit and Implicit.
Explicit coercion is an obvious attempt from the author to convert a value of one type to another type. Implicit coercion occurs as a less-obvious side effect of another operation. See the below examples(gist):
Note that in the example above that both approaches, implicit and explicit, result in the same outcome, it is the how that is interesting and results in some debate. Namely readability being the point of contention. Almost always, someone other than you is going to be reading your code. Which of the above methods is more readable?
With all that being said, let’s take a look at how JS handles comparisons between data types using
===, and also when using
Here are some code examples, explained in more detail below(gist):
The main takeaways from the code above are:
nullis an Object
undefinedis it’s own distinct type undefined
OK, let’s force the JS interpreter to make some guesses as to our intentions:
null equal each other with the Equality Comparison(4–5) but not with the Strict Equality Comparison(8–9)
Let’s look at some String, Number, and Boolean comparisons:
By now you may notice a pattern. When comparing vals of different types using the Equality comparison, JS will likely correctly coerce the values. Accuracy though is achieved through the Strict comparison.
In the end coercion is a necessary evil of untyped languages.
My suggestion is:
As you are writing code ALWAYS use the Strict Comparison unless you can justify not doing so.
As always, let us know your thoughts and questions and PLEASE follow us on twitter. Keep after it.
Create your free account to unlock your custom reading experience.