Search code examples
javascriptpost-incrementoperator-precedence

JavaScript order of operations - parentheses are not evaluated before post-increment operator


Example 1:

var a = 0;
var b = 1;
a = (b++);
console.log(a);

a is equal to 1 which is the same, with or without the parentheses. Example 2:

var a = 0;
var b = 1;
a = b++;
console.log(a);

I understand the second example. b is assigned to a, then incremented to 2. But in the first example, why don't the parentheses force b to increment to 2 before assigning the value to a given parentheses have the highest operator precedence? Thanks.


Solution

  • The explanation by T.J. is a good one on the theoretical level of what's going on, but here is another explanation from a different angle (more practical than theoretical):

    We have two similar expressions b++ and ++b. Both mean b = b + 1, but they work differently.

    b++ evaluates to the current value of b (which is 1), then increments it. It's equivalent to:

    var a = 0;
    var b = 1;
    a = b;
    b = b + 1; //(b + 1) makes no difference
    console.log(a);

    ++b does the opposite, increments b, then evaluates to the incremented value. It's equivalent to:

    var a = 0;
    var b = 1;
    b = b + 1; //(b + 1) makes no difference
    a = b;
    console.log(a);

    Now, notice that adding parentheses surround b + 1 in any of the above examples will make no difference because the assignment a = b is done in a different step. Similarly, adding parentheses to b++ will not make any difference because the assignment to a and the incrimination are done in two different steps.

    However, the parentheses around b++ are actually equivalent to parentheses around b on the line a = b in the code above, not around b + 1 as you seem to think from your question. And it is clear that the parentheses a = (b) don't make any difference.

    EDIT As you suggested in your comment, if we think of b++ as an implicit function, then the body of the function is similar to T.J.'s explanation:

    1. Save the value of b (1), let's say to an implicit variable x
    2. Increment b to 2
    3. and return x

    Putting parentheses around the function call is like putting them around the returned value which is 1. Here is a demo:

    var a = 0;
    var b = 1;
    a = bPlusPlus(); //(bPlusPlus()) makes no difference
    console.log(a);
    
    function bPlusPlus() {
      var x = b;
      b = b + 1;
      return x;
    }