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
+
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...)
.