Adding and subtracting strings and numbers in Javascript - auto type conversion?

Let's look at the following Javascript code.

<script type="text/javascript" lang="javascript">
    function test()
    {
        alert('2'+8);
        alert(8-'2');
    }
</script>

In the first alert box, it displays the result of concatenation of 2 and 8 which is 28. In the second alert box, however it displays the subtraction of two numbers which is 6. How?


Solution 1:

The + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed. The - is not overloaded in such a way and all operands are converted to numbers.

From the specification:

11.6.1 The Addition operator ( + )

(...)
7. If Type(lprim) is String or Type(rprim) is String, then

  • Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).
(...)

11.6.2 The Subtraction Operator ( - )

(...)
5. Let lnum be ToNumber(lval).
6. Let rnum be ToNumber(rval).
7. Return the result of applying the subtraction operation to lnum and rnum.
(...)

Solution 2:

+ is used for both string concatenation and addition. If either operant is a string, concatenation is used. - is only used for subtraction, both operants are always cast to numbers.

Solution 3:

+ is used for both concatenation and addition, but when used with a string, defaults to concatenation. - cannot be used on strings, so its operands are converted to numbers.

Edit: This is not meant to be identical to the above post! XD

Solution 4:

1st: it casts 2nd operand to the 1st operand (String), because + is used for strings concat too.

2nd: it casts 2nd operand to a Number, because - is just used for numbers operations.