Type Coercion with the ‘+’ and ‘-’ Operators in JavaScript — How Exactly Does it Work?
Chances are you may have already seen this meme. Today we will see how + and - work in JavaScript with respect to type coercion. Let’s see how the + operator works.
What ECMAScript specification says is that if at least the type of one of the two operands is a string, then the + operator converts both operands to string and then does string concatenation.
If the type of both the operands are Number, then JavaScript does numeric addition.
In Image 1, we have x=“11” and y=1, here the type of x is string. So, x+y become “11”+”1". As the result of concatenation, we get “111”.
Now let’s see how the - operator works.
ECMAScript specification says that the - operator tries to convert all operands to Number. So, now we’re are left with 11–1. As the result of numeric subtraction, we get 10.
More content at plainenglish.io