Because:
- JavaScript is a sucker
- JavaScript does maths!
JavaScript is a dynamically typed language which means that values do not have types. In reality, they contain different types (such as strings
, number
or. ) however, variables can alter their type when JavaScript believes they are required to.
I’m not going to go over how JavaScript changes the types however, I’ll try to explain the reason JavaScript provides the answers you’re looking for in your question.
"11"+ 1 = 111
JavaScript detects the fact that “11” is a string
and is able to see that an element gets added. It tells itself, “Huh. There’s something added to an existing string. Does this sound right to you? What should I do if something is added to strings?” Then it sees that the “rule” when using +
when using an string
is to add the item that’s being included to string
. It converts one
(a numeral at this moment) into an unicode strings (“1”). It then smashes it after the “11”, and you receive “111”.
Let’s now look at:
"11"- 1 = 10
JavaScript recognizes the fact that “11” is a string
and is able to see that something is removed from the string. It thinks to itself “Huh. Something is subtracted from strings. Does this seem to make sense? What should I do when you subtract something from strings?” It doesn’t have an established rule!
Then it states, “Well, that second argument, 1
is a number. What if I transform one of the arguments, the "11"
, into an actual number. What can I do?” It turns out that yes, you is possible to transform”11″, the code "11"
into the form of a number.
Then it asks “Does subtracting one number to another one make sense? Does there exist a formula to subtract the same number by the other?” It turns out that it knows how to subtract one number by another. It converts the string “11”, to the number 11, subtracts 1, it, and shows the result as 10.
It’s among the bizarre effects of a language that is dynamically typed.