What is Implicit Type Coercion?
In smaller programs, these anomalies can be easily caught and rectified, but when the code base grows it becomes almost impossible to catch these.
Let us see one of these anomalies with some more detail.
Now lets break this down
- 0 is a number.
- “0” is a string with a 0.
-  is an empty array.
- “\t” is a string with a tabspace.
and we know that 0==0 so hence we get true.
Now, this one seems a bit weird but it follows the same rules as the one above.
Let me break it down for you. Like I said in the previous case in a string to number comparison the string always gets type converted into a number by the ToNumber abstract operation. Hence we can represent the comparison like this,
What the Number() does is it internally uses the ToNumber abstract operation on the character gets passed to it and guess what the numerical value of white space is 0.
Now we have 0==0 which is true.
To be honest, this one got me the first time too, But trust me this behavior is completely standard.
We saw in the previous cases that when doing a string-to-number comparison the ToNumber operation gives us the numerical value which we use for the comparison, this case is no different.
The thing is ToNumber will use two more internal operations, ToPrimitive and [[DefaultValue]].
ToPrimitive will take 2 arguments in our case the array and the hint type(the type we need it converted to) which is Number.
Now the ToPrimitive calls the [[DefaultValue]] operation also with the hint type Number. The [[DefaultValue]] operation tries to convert the given value into a primitive type. In our case, the array we pass gets converted into a string.
Now lets do the string to number conversion.
And finally the moment we have been waiting for! The empty array has been type converted into a number!
And our expression ends up looking like this 0==0 which is true!
Now about the other cases
In the three falsy cases we have String to String comparison and String to Object comparison. Let’s look at these cases.
String to String Comparison
Both the values are of type string which is a primitive type and hence no type coersion takes place. So obviously “0” will not be equal to “\t”.
String to Object Comparison
The above examples can be expressed as follows
Intresting isn’t it?
If you are curious about the rules followed in these conversions
On a closing note, I’d like to mention something that I should have mentioned at the start of this blog.
Don’t use == for comparision😂
Use === which compares the type and the value.
And also there is this awesome thing called Typescript, Which overcomes all of this implicit type coercion nonsense by using strong typing.
So in conclusion switch to typescript!