DEV Community

Cover image for Automatic type conversion in Javascript, or why "3"+2="32" and "3"-2=1
Oleksandr Demian
Oleksandr Demian

Posted on

Automatic type conversion in Javascript, or why "3"+2="32" and "3"-2=1


A lot of people are saying that javascript is poorly designed because of this:
type conversion
I mean, why should one go and learn why this happens, if he/she can just say: "javascript is stupid".

The general problem is that today everyone can write code (especialy javascript), but not everyone should. Anyway, let's dive into "Automatic type conversion in Javascript"


"Javascript is so stupid. Look, I'm summing string and number expecting a number as result"
Alt Text

Automatic type conversion in Javascript

Javascript is dynamicaly typed programming language. As the result, it will automaticaly convert data to the most appropriate type. Ex:
Alt Text
In the example above, object is parsed as boolean, because if statement only works with boolean type. The same is true for any other type (number, string, function, ecc - they all will be parsed as boolean).

Now, let's get into the original problem. Why "3"+2="32" and "3"-2=1. Imagine if you were a Javascript engine (like V8 or SpiderMonkey). You wouldn't see it as "a number as string plus number". You will see: "string value plus number value". As sum operator is also used for concatenation, once you see there is a string in the statement, it makes sense to concatenate all the values as strings, so (string)"1" + (number)1 = (string)"11" (you don't know if string can be parsed as number, and it wouldn't makes sense to do the check. You don't do arithmetic operations with words, even if they do represent number).

In case of subtraction things are different. You cannot subtract strings, so it makes more sense to parse everything as numbers, because subtraction is an arithmetical operation (meanwhile sum is also a concatenation). Same thing for multiplication and division.

W3Schools has a good article that shows all the possible type conversions in javascript:

PS. The reason behind this article is not to explain why "3"+2="32", but to show that there is more to programming than writing code (a reputable developer needs to learn/do research on why things happen instead of saying they are stupid).

Discussion (1)

perpetualwar profile image
Srđan Međo

Yep, bashing js is just a popular thing to do nowadays... The other day I saw someone trying to compare object with boolean and wondering why it is false... But ye easier to say js sucks. People, right?