+ 3

Why does 4 -"8" return as -4 while 7 +"2" returns as 72 in js?

7th Jul 2020, 7:43 AM
Hridita Paul
Hridita Paul - avatar
5 Antworten
+ 2
I think, + is overloaded operator for concatenation of string (it is only one overloaded operator in java, i think it is same in JavaScript, and in most other languages). So string1.concat(string2); is same as string1+string2. But where as - (minus) is just arithmetic operator only so it perform arithmetic subtraction. Edit: Yes. You can find the reason from here... https://www.google.com/amp/s/www.digitalocean.com/community/tutorials/how-to-do-math-in-javascript-with-operators.amp
7th Jul 2020, 8:06 AM
Jayakrishna 🇮🇳
+ 2
There are 2 things that the plus(+) operator does. If it is used with just numbers then it will do arithmetic operations. And if it is used all string or even single string then it will do string concatenation. But minus(-) operator does only one thing which is to subtract value. console.log(5+5); //10 console.log(5-5); //0 console.log(5+'5'); //55 console.log('5'+'5'); //55 console.log('5'-'5'); //0 console.log(5 + "hello"); //5hello console.log(5 - "hello"); //NaN
7th Jul 2020, 8:54 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
Thank you guys!
8th Jul 2020, 4:00 AM
Hridita Paul
Hridita Paul - avatar
+ 1
Sorry, Jayakrishna but i couldn't find it. Can you please tell me?
7th Jul 2020, 8:49 AM
Hridita Paul
Hridita Paul - avatar
0
Hridita Paul the link will provide you explanation about + operator. You have already got examples by @Rick Grimes. And I think you only confused about "what is overloading". It means, here the operator can be used for more than one perpuse, it works or operates depends on the operands. So if it operated with numbers then perform addition, if operated with string, then it performs concatenation.. It is also treated as polymorphism (one of oops principles). Hope it helps you...
7th Jul 2020, 9:15 AM
Jayakrishna 🇮🇳