In my last post I explained the difference between using == and ===. In this post I’m going to talk about type conversion in JavaScript.

(2 + 2) * (2 + 2);
('2' + '2') * ('2' + '2');

What do you think the answers are? It should be 16, right? Well, it should be, and the first equation does have an answer of 16. That second equation though is a little bit weird.

Look closely and you’ll see that the numbers are not actually numbers….they are in fact strings. JavaScript uses the plus sign to concatenate two strings, so what actually happens here is the strings are pushed together to result in 22.

This ends up looking like this: (‘22’) * (‘22’).

What happens next is where things start to get interesting. The ‘22’ is still in a string, but the JavaScript doesn’t really know what to do with two strings that should be multiplied.

Rather than throw an error that you can’t multiply two strings, JavaScript instead tries to help by converting the string to a number. So (‘22’) * (‘22’) ends up being 484. It’s good to note that JavaScript does not covert the number back to a string afterward.

If you would like to a take a closer look, you can check out my JSFiddle here.

Wait, wait, wait, you think. What happens if you multiply two strings that are actually letters. Like this: ‘what’ * ‘happens’ * ‘if’. (This is also in the JSFiddle, if you want to check that out.)

Well the type conversion still happens, but because you can’t actually multiply ‘what’ * ‘happens’ * ‘if’, the result it will give you is NaN, or Not a Number.

Kinda weird … but kinda cool, right?

Questions? Tweet me!