11.6.1 The addition operator

2010-05-17

This operator either adds two numbers together or concatenates to strings. Basically, when the primitive value (ToPrimitive) of either operand is of type string, both sides are concatenated. Otherwise they're mathematically added as numbers (ToNumber).

AdditiveExpression : AdditiveExpression + MultiplicativeExpression

Code: (Meta Ecma)
function evaluate(AdditiveExpression + MultiplicativeExpression) {
var lref = evaluate(AdditiveExpression);
var lval = GetValue(lref);
var rref = evaluate(MultiplicativeExpression);
var rval = GetValue(rref);
var lprim = ToPrimitive(rval);
var rprim = ToPrimitive(lval);
// concat strings?
if (Type(lprim) == 'string' || Type(rprim) == 'string') return ToString(lprim)+ToString(rprim);
// add numbers together
var lnum = ToNumber(lprim);
var rnum = ToNumber(rprim);
if (isNaN(lnum) || isNaN(rnum)) return NaN;
if (IsInfinite(lnum) && IsInfinite(right)) {
if (Sign(lnum) != Sign(rnum)) return NaN;
return lnum;
}
if (IsInfinite(lnum)) return lnum;
if (IsInfinite(rnum)) return rnum;
if (lnum === -0 && rnum === -0) return -0;
if (lnum === 0 && rnum === 0) return +0;
if (lnum === 0) return rnum;
if (rnum === 0) return lnum;
if (lnum < 0 && rnum > 0 && -lnum === rnum) return +0;
if (rnum < 0 && lnum > 0 && -rnum === lnum) return +0;
// rnum and lnum are now finite, nonzero and not NaN.
return lnum - rnum;
}

Note that no hint is provided to ToPrimitive. All native objects use Number as the default hint when none is given. Date uses string. ToPrimtive can still return strings, even when the hint Number is used (it's only a hint).

Note that it's always the case that when a and b are two numbers, a-b === a+(-b).