Adding Numbers In JavaScript

28 July, 2008 | JavaScript

You think I’m joking right? Well due to a silly mistake when creating the language the concatenation character is the plus symbol. The same symbol used when you are adding numbers together and so 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 it. 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.

Write a comment