Search code examples
javascriptoperatorstype-conversioncoercion

How does JavaScript treat the ++ operator?


JavaScript does funky automatic conversions with objects:

var o = {toString: function() {return "40"; }};
print(o + o);
print((o+1)+o);
print((o*2) + (+o));

will print:

4040
40140
120

This is because +, if any of the arguments are objects/strings, will try to convert all the arguments to strings then concatenate them. If all arguments are numbers, it adds them together. * and unary + convert objects to numbers using toString (as well as valueOf, not shown here).

What does JavaScript do for the ++ operator?


Solution

  • From ECMAScript Language Specification

    11.3 Postfix Expressions

    Syntax

    PostfixExpression :

    • LeftHandSideExpression
    • LeftHandSideExpression [no LineTerminator here] ++
    • LeftHandSideExpression [no LineTerminator here] --

    11.3.1 Postfix Increment Operator

    The production PostfixExpression : LeftHandSideExpression [no LineTerminator here] ++ is evaluated as follows:

    1. Evaluate LeftHandSideExpression.
    2. Call GetValue(Result(1)).
    3. Call ToNumber(Result(2)).
    4. Add the value 1 to Result(3), using the same rules as for the + operator (section 11.6.3).
    5. Call PutValue(Result(1), Result(4)).
    6. Return Result(3).

    This is pseudo javascript code of how postInc works:

    function postInc(a) {
      var x = +a; // Converts a to a number, Section 11.4.6 Unary + Operator
      a = x + 1;
      return x;
    }
    

    Edit: As mikesamuel said: it's not parseInt. Updated to reflect that.