Why in JavaScript "11" + 1 = 111 but "11" - 1 = 10 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why in JavaScript "11" + 1 = 111 but "11" - 1 = 10 ?

Please explain this. Thanks.

20th Sep 2019, 5:36 AM
Umesh Kushwaha
Umesh Kushwaha - avatar
3 Answers
20th Sep 2019, 7:27 AM
David Carroll
David Carroll - avatar
+ 5
In Javascript, strings can be concatenated, so thats what the browser thinks you are doing and converts the 1 into the string when you add it Strings can not be subtracted though, so the interpreter converts the string to an integer in the second one Javascript is irritating this way
20th Sep 2019, 5:45 AM
Trigger
Trigger - avatar
+ 2
In the first case, a string merge operation is performed, not an arithmetic operation. In the second case, a subtraction operation is performed. The interpreter tries to cast everything to the same type. Read it in the section about explicit and implicit conversion of data types
20th Sep 2019, 6:57 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar