My Understanding Of Javascript Type Coercion

This week I got to debug a fun Javascript bug. I was using the double equal signs to compare two arguments and under certain cases the code would produce an error. After a bit of digging I learned about Javascript type coercion and the differences between double equals and triple equals. To illustrate the issue lets fire up node and create two variables:

$ node

> var i = 23;

> var j = "23";

The first variable listed above is an integer with the value 23. The second variable is a string with the number 23. If we compare these two values with double equals we get a successful comparison:

> i == j

If we use triple equals we get a very different result:

> i === j

Why is this? In the first example javascript will convert the values to the same type and then compare the result. This is called type coercion. In the second example javascript will compare the two variables AS IS resulting in a failed comparison operation. This was an interesting finding and I’m sure this has bit more than one developer. This definitely gives me a huge appreciation for statically typed languages.

This article was posted by Matty on 2017-11-29 09:14:42 -0500 EST