The following all expressions in JavaScript are far obvious.
var x = 10 + 10;
The value of x is 20.
x = 10 + '10';
The value of x in this case is 1010 because the + operator is overloaded. If any of the operands is of type string, string concatenation is made and if all the operands are numbers, addition is performed.
x = 10 - 10;
x = 10 - '10';
In both of these cases, the value of x will be 0 because the - operator is not overloaded in that way and all operands are converted to numbers, if they are not before the actual subtraction is performed (you may clarify, if anyway I’m wrong).
What happens in the following expression.
x = '100' - -'150';
The value of x is 250. Which also appears to be obvious but this expression somewhat appears to be the equivalent to the following expression.
x = '100' +'150';
If it had been the case then these two strings would have been concatenated and assigned 100150 to x. So why is addition performed in this case?
EDIT :
+'10' + 5 returns 15 and 'a' + + 'b' returns aNaN. Does anyone know why?
In your case
- -is not evaluated first to become equivalent to+.-"150"is evaluated as a number, and so became-150.As you can’t subtract a string (
NaN), JS then take"100"and make a number, and then it run100–-150which is 250.The key is really that you can’t subtract type string, so it converts those strings to numbers.