DEV Community

Kashif Raza
Kashif Raza

Posted on

Do you know why in JavaScript is "11" + 1 = 111, but "11" - 1 = 10?

Top comments (7)

Collapse
 
dreiv profile image
Andrei Voicu

Short answer: you can add strings, but you cannot subtract them, and addition is also used in numbers :D

Collapse
 
raggiodev profile image
Fernando Andrés Raggio

Easy peasy. You know 😁

Collapse
 
kashifraza profile image
Kashif Raza

Good reply 😃

Collapse
 
peledzohar profile image
Zohar Peled

Last time I've used Javascript was about 7 or 8 years ago - But:

The + operator in Javascript (as in many other languages) have two different Jobs: It acts as an addition operator, and as a string concatenation operator.

Since Javascript is a weakly typed language, implicit conversions are everywhere.

When the Javascript engine sees "11" + 1 it implicitly converts the numeric 1 to a string, therefor the + here acts as a string concatenation operator, and the result is "111", which is a string, not a number.

The - operator, however, has no effect with strings. Try "asdf" - "a" and see what happens.
Therefor, in this case, the Javascript engine implicitly converts the string "11" to a number, and the result 10, which is a number, not a string.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I would say that the first is type coerced from a string and the second is 2 numbers. Perfectly normal nobody panic 😅.

Collapse
 
vetler profile image
Vetle Leinonen-Roeim

Not sure I want to know.

Collapse
 
moopet profile image
Ben Sinclair

Yes.