Why does JavaScript handle the plus and minus operators between strings and numbers differently?

前端 未结 7 1896
再見小時候
再見小時候 2020-11-22 10:21

I don\'t understand why JavaScript works this way.

console.log(\"1\" + 1);
console.log(\"1\" - 1);

The first line prints 11, and the second

7条回答
  •  不知归路
    2020-11-22 10:51

    + is ambiguous. It can mean "concatenate" or "add". Since one side is a string, it is taken to mean "concatenate", hence the result is 11 (which, by the way, was one of my favourite jokes as a young child. That and "1 + 1 = window", as shown visually: │┼│ ニ ⊞)

    - however has only one meaning: subtract. So it subtracts.

    This kind of problem is not present in other languages such as PHP, where "concatenate" is . instead of +, making no ambiguity. Still other languages like MySQL don't even have a concatenation operator, instead using CONCAT(a,b,c...).

提交回复
热议问题