The code you show will not work the way you describe. It will result in 7
.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt()
[docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix
) to ensure the casting from string to number uses the base you expect. (The lack of info on radix
in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt()
.)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN()
[docs].