Or used String Concatenation?
object (for those wondering what is the type of array, arrays are a special type of object)
But for the focus of this article, we would be focusing only on the most commonly used types which are: boolean, string, and number.
Type Coercion is the conversion of one type to another. There are two forms of Type Coercion: Explicit and Implicit.
Explicit Coercion is the conversion of a value from one type to another using explicit methods such as Number(), parseInt(), and String().
Implicit Coercion is the automatic conversion of one type to another.
We would be focusing on Implicit Coercion instead as that is where most of the bugs occur.
One common place where Implicit Coercion tends to occur is through String Concatenation.
Another common use case is through the short-hand usage of Evaluation of Truthy Values.
These occur typically in if statements (if (x)), ternary operators (x ? 1 : 0), and basically any place in code where a non-Boolean variable is being treated as a Boolean value.
That is why it is dangerous to use these short-hand syntaxes if you do not know all the edge cases when converting a non-Boolean type to a Boolean type.
Another common area where Implicit Coercion occurs is through the usage of ‘==’.
If you are curious, you can check out the algorithm for Implicit Coercion, here.
You can play with the examples above in this JSFiddle.
I hope that after reading this article you would think twice about using these unsafe methods. You can see how by not carefully considering all the edge cases of Type Coercion, bugs can easily occur.
Utilising ‘===’ instead of ‘==’ always
Using ESLint, to throw warnings and errors when you write these code
Using TypeScript, to help detect potential run-time errors beforehand
Did you know? Someone even took this Type Coercion concept to the extreme and made a programming language out of it.
If you felt that you have learned something new, do feel free to follow 🥰, drop a react 💖 or write a comment ✍️!
It helps makes me create and share more valuable content for you to become a better Web Developer! 🤗