Quote:
Originally Posted by microbet
Why? Is it just that they wanted += to concat strings so they made it work, but didn't want -= to do anything to strings so they made it treat it as a number?
Or is there a deeper, more structural reason?
No, there's not a deep structural reason. Javascript tries to cast values into something that makes sense when it can. If there's more than one way a casting could be done, then it has a preferred method and uses that.
Forget += and -= for now, because + and - have the same semantics in javascript, i.e.
"0" + 1 = "01"
"0" - -1 = 1
(and also "0" - "-1" = 1 and 0 - "-1" = 1)
In the plus case, there are 2 ways you could do conversions to make it work. They arbitrarily chose to convert the number to a string. This is true whether you do "0" + 1 or 0 + "1".
In the minus case, there's only one way to have the operation make sense because there isn't a valid JS expression that is "string - string". So the string gets converted to a number. If the conversion doesn't work you get NaN
Most languages that do automatic conversion have some version of this problem, unless they don't have any operators that have ambiguities like this. For example, if you couldn't use "+" to concatenate strings at all, this wouldn't happen, but using "+" to concatenate strings is nice.