+ 10

Why does "21"+1 give "211"(string) but "21"-1 gives 20 (a number) in JavaScript?

7th Aug 2020, 3:31 PM
Takudzwa Nelson Chiutaalenga
Takudzwa Nelson Chiutaalenga - avatar
2 Respostas
+ 7
"+" operator when used with strings concatenates them but when it used with integers it adds them, here 1 is implicitly converted to string as well as other operand is string and concatenation takes place , while "-" operator has no meaning for strings ,so "21" is implicitly converted to integer and subtraction takes place Also you can go through this link for better understanding https://dmitripavlutin.com/javascriptss-addition-operator-demystified/
7th Aug 2020, 4:05 PM
Abhay
Abhay - avatar
+ 3
Since you have string and number and when you make + string has overloaded + operator so integer convert to string and you got concatenate - not overloaded in string but do in number so string convert to number and return 20 if string could not convert to number you got error or undefined(do not remember which one)
7th Aug 2020, 5:51 PM
george
george - avatar