Let\'s look at the following Javascript code.
If you don't want this, an easy fix is: (1*'2')+8 JSYK
The +
operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed. The -
is not overloaded in such a way and all operands are converted to numbers.
From the specification:
11.6.1 The Addition operator ( + )
(...)
7. If Type(lprim) is String or Type(rprim) is String, then
- Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).
(...)11.6.2 The Subtraction Operator ( - )
(...)
5. Let lnum be ToNumber(lval).
6. Let rnum be ToNumber(rval).
7. Return the result of applying the subtraction operation to lnum and rnum.
(...)
1st: it casts 2nd operand to the 1st operand (String), because + is used for strings concat too.
2nd: it casts 2nd operand to a Number, because - is just used for numbers operations.
+
is used for both concatenation and addition, but when used with a string, defaults to concatenation. -
cannot be used on strings, so its operands are converted to numbers.
Edit: This is not meant to be identical to the above post! XD
+
is used for both string concatenation and addition. If either operant is a string, concatenation is used. -
is only used for subtraction, both operants are always cast to numbers.