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

前端 未结 7 1927
再見小時候
再見小時候 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:47

    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.

提交回复
热议问题