Why does JavaScript evaluate plus with a string and integer differently than minus?
An example:
console.log(1+"1");
console.log(1-"1");
The first line prints "11" and the second prints 0.
Why does JavaScript evaluate plus with a string and integer differently than minus?
An example:
console.log(1+"1");
console.log(1-"1");
The first line prints "11" and the second prints 0.
The +
operator is given a specific meaning with strings, but the -
operator is not. So, when you try to use the +
operator and one of the operands is a string, JavaScript casts the integer to a string and then does concatenation instead of addition. However, when you use the -
operator, because that operator has no defined behavior with strings, JavaScript casts the string to an integer and then does subtraction.
Because the plus sign implicitly converts 1 to a string
And the minus sign implicitly converts "1" to an int.
Per Request
tl;dr; The ECMA 5 spec states that if the left or right side of the operator is a string then return the string result of concatentating. Where as the minus operator just operates on numbers so it will convert both sides to numbers
11.6.1 The Addition operator ( + ) # Ⓣ Ⓡ Ⓖ The addition operator either performs string concatenation or numeric addition.
The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
Let lref be the result of evaluating AdditiveExpression.
Let lval be GetValue(lref).
Let rref be the result of evaluating MultiplicativeExpression.
Let rval be GetValue(rref).
Let lprim be ToPrimitive(lval).
Let rprim be ToPrimitive(rval).
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)
Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.
NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.
NOTE 2 Step 7 differs from step 3 of the comparison algorithm for the relational operators (11.8.5), by using the logical-or operation instead of the logical-and operation.
11.6.2 The Subtraction Operator ( - ) # Ⓣ The production AdditiveExpression : AdditiveExpression - MultiplicativeExpression is evaluated as follows:
Let lref be the result of evaluating AdditiveExpression.
Let lval be GetValue(lref).
Let rref be the result of evaluating MultiplicativeExpression.
Let rval be GetValue(rref).
Let lnum be ToNumber(lval).
Let rnum be ToNumber(rval).
Return the result of applying the subtraction operation to lnum and rnum. See the note below 11.6.3.