The following JavaScript expressions are pretty 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 performed, and if all operands are numbers, addition is performed.
x = 10 - 10; x = 10 - '10';
In both cases, the value of x will be 0 , because the - operator - not overloaded in this way, and all operands are converted to numbers if they are not before the actual subtraction (you can clarify if I am mistaken in any case).
What happens in the following expression.
x = '100' - -'150';
The value of x is 250 . Which also seems obvious, but this expression looks somewhat equivalent to the following expression.
x = '100' +'150';
If that were the case, then the two lines would be merged and assigned 100150 to x . So why is the addition done in this case?
EDIT:
+'10' + 5 returns 15 and 'a' + + 'b' returns aNaN . Does anyone know why?
javascript
Tiny
source share