The + operator in Javascript is overloaded: it performs two quite distinct functions. It performs arithmetical addition on numbers, but concatenation on strings. The latter always takes precedence over the first, so if a string is involved on either side of the operator, concatenation will occur. That is to say:
Code:
1 + 1 == 2;
1 + "1" == "11";
"1" + 1 == "11";
If you're not sure whether you're dealing with a number or a string, be safe and convert it. There are several methods of doing this:
Code:
new Number(n);
parseFloat(n, 10);
parseInt(n, 10);
n - 0;
-n;
+n;
n * 1;
Bookmarks