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.
Top comments (4)
Here is one :
If you place a "+" immediately before a String Number it will be converted to a Number Type.
"11" - 0 + 1yields
"11" + 1 - 0yields
111... order of operations can be important!
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.