JavaScript operators

In JavaScript "11" + 1 is 111,
but "11" - 1 gives 10
How?
Can anyone please help me with this ?

1 Like

so after reading the entire thing on the link u did gave me
i could only figure out the next:

the “” makes the “11” a string
the + sign is an arithmetic operator
and u have a num
a num is true
a string is false

true true  = true so they added 1

arithmetic operators ( - + * / % ). Note, that binary + does not trigger numeric conversion, when any operand is a string.

then we have
again a string “11”
another - arithmetic operator but - is false
another num
Boolean(-0) // false
so it becomes
false + false = false the -1 is then substracted

How does it help the persone above excatly?

1 Like

It explains, in full, JavaScript’s type coercion rules. And in this case, implicit type coercion is the thing that applies.And the article explains this in detail.

If you don’t understand, or didn’t read that far:

In situations with an operator (eg a + b, c - d), JavaScript coerces types so that they are the same on both sides. So for

"11'" - 1
string - number

The types on both sides have to be a number, it makes no sense otherwise. So coerce string → number. As long as it can convert to a number, that will work.

"11" + 1
string + number

The types here either have to both be string or both be number, because + is either addition or concatenation. With +, JS always tries to coerce to string, so "11" + "1" is “111”.

5 Likes

Javascript’s type system is basically insane. Don’t try to look for a ton of consistency in it.

2 Likes

Thank You so much guys for your response