Adding Numbers In JavaScript

28th July 2008 - 2 minutes read time

You think I'm joking right? Well, due to a silly mistake (in my opinion) when creating the language the concatenation character is the same as the plus symbol. This means that sometimes JavaScript will add them together and sometimes it will concatenate them.

This occurs if JavaScript encounters any part of the calculation to be a string. If it is then it will concatenate the whole expression. For example.

alert("1"+2+3);// prints out "123" rather than 6

To stop this you need to add the parseInt() function to the part of the addition that might be mistaken as a string. Or the whole thing just to make sure. The following is a bit of an overkill but ensures that the values will be added, NOT concatenated.

alert(parseInt(1)+parseInt(2)+parseInt(3));

It is especially important to do this if you get any values from any form fields. This is because they are passed to JavaScript as strings so you will need to parseInt() the values to work with them. If you try to directly add two form values you will just end up concatenating them

Add new comment

The content of this field is kept private and will not be shown publicly.