Type Coercion with the ‘+’ and ‘-’ Operators in JavaScript — How Exactly Does it Work?

zmjdev
JavaScript in Plain English
2 min readJan 9, 2021

--

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.

Image from https://www.ecma-international.org/ecma-262/#sec-addition-operator-plus

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.

Image 1

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.

Image from https://www.ecma-international.org/ecma-262/#sec-subtraction-operator-minus

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

--

--