zunami

Posted on

# Today I answered a question which has been bothering me for a long time.

### Hey!,

today I started a little bit with the semantics of Javascript and answered me on of the questions I have since I started with this language. This made the language for me a little bit illogical. But which question? Its the question why
if I do a addition with a string and a int it the string joins with the string,

``````"11" + 1 = "111"
``````

and if I do a subtraction the string becomes subtracted like int minus int.

``````"11" - 1 = 10
``````

That was the question which bothered me a long time. Today I found the answer in the ECMAScript semantics.

On page 294 is the semantic for the addition operator (+) which is not only used to add two numbers or more, no its also used to join strings and if one of the given values is a string it converts both values (if the string contains a number not something like "eleven" it must be "11") to a string and return it as a joined string.

And the Subtraction Operator (-) converts both values to a number (if possible) and then it subtracts them.

And it makes the language now a bit more logical for me I hope for you too. I'm sorry for my English btw I'm learning it currently.

Its my first blog post if you have feedback please leave a comment.

Sources:

## Top comments (4)

Mohsen Alyafei

Nice.

Here is one :

``````a = 1 + "11";   // "111"
b = 1 +"11";    // "111"
c = 1 + +"11";  // 12

console.log(a)
console.log(b)
console.log(c)
``````

If you place a "+" immediately before a String Number it will be converted to a Number Type.

zunami

Yeah, correct!

Nathan Kallman

And `"11" - 0 + 1` yields `12` while `"11" + 1 - 0` yields `111` ... order of operations can be important!

zunami

If we calculate ("11" - 0) we get a number again and then if we add 1 we have not anymore the string case. On the other example with ("11" + 1) here we have the case with string join and then it joins if we subtract it by 0 it will be the same but if we subtract it with a different number it will be converted into a number. But yes you are right its important to check the order of operations. The explanation is just for those who don't understand it.