Search code examples
javascriptincrementmultiplication

How works multiplication just after incrementation (i++ * 2) in Javascript?


Please read whole topic, before post answer. No answer found to this question in post: ++someVariable Vs. someVariable++ in Javascript

var i = 1;
i = i++ * 2; // i = 2, .. why not 4 ?

interpreter does the multiply (1*2), but where is the increment ( i++ )?

var i = 1;
i = ++1 * 2; // i = 4 

I'm understand, that the i++ does the increment after the statement, ++i does it before the statement, but in this example: i = i++ * 2 // (1*2), how the interpreter works?, where is the increment of i in this case? maybe i = (1*2)+1 )), or i = (1*2) and no more i exist, and nothing to increment??

HOW ?

P.S. I think, it is a wrong question, but as Brooks Hanes said(in comment), this is a learning example.


Solution

  • This is an interesting little problem, a simple experiment shows what is happening. jsFiddle

    var i = 3; p = i++ *2; console.log(i, p);
    

    The 2 is multiplied by i (3) the result (6) is placed in p. Then a copy of the original value of i (3) is incremented and placed back in i. This behaviour is logically consistent with the following:

    var i = 3; var p = 0; function adder(x) { p = x + 2; }; adder(i++); console.log(i, p);
    

    This makes a strange kind of sense because the post increment is supposed to happen after the statement.