Using the node.js console, I get the following unexpected results:
> 2 + "3" "23" > 2 * "3" 6
Why does the first example favor string concatenation and integer multiplication in the second example? I would not expect concatenation between different types, but rather an error to be thrown. If this is the behavior in JS, how can I predict the type of the final result?
According to ECMAScript 2015 Language Specification (Addition operator, Multiplicative operators), the evaluation of additive expression is (
lprim is the left primitive (lval converted to primitive),
rprim is the right one):
... If Type(lprim) is String or Type(rprim) is String, then Let lstr be ToString(lprim). ReturnIfAbrupt(lstr). Let rstr be ToString(rprim). ReturnIfAbrupt(rstr). Return the String that is the result of concatenating lstr and rstr. Let lnum be ToNumber(lprim). ReturnIfAbrupt(lnum). Let rnum be ToNumber(rprim). ReturnIfAbrupt(rnum). Return the result of applying the addition operation to lnum and rnum.
The evaluation of multiplicative expression is:
... Let lnum be ToNumber(leftValue). ReturnIfAbrupt(lnum). Let rnum be ToNumber(rightValue). ReturnIfAbrupt(rnum). Return the result of applying the MultiplicativeOperator
You can see that if it is an additive expression, it is first to check whether there is a String. If there is a String, string concatenation is executed. Otherwise, the values are converted to Number and an addition operation is executed.
If it is a multiplicative expression, it would always convert values to Number and deliver a multiplicative operation.