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

Nirgn picture Nirgn · Jun 24, 2014 · Viewed 20.9k times · Source

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 prints 0. Why does JavaScript handle the first as a String and the second as a number?

Answer

Bernhard Hofmann picture Bernhard Hofmann · Jun 24, 2014

String concatenation is done with + so Javascript will convert the first numeric 1 to a string and concatenate "1" and "1" making "11".

You cannot perform subtraction on strings, so Javascript converts the second "1" to a number and subtracts 1 from 1, resulting in zero.