javascriptincrement

javascript Postfix and Prefix Increment in expression


I'm having trouble understanding how work Postfix and Prefix Increment in expression like this:

var x = 1;
x = ++x + x++ * x

Why browser console return 8 ?


Solution

  • It is evaluated left to right:

    ++x           : x is now 2
    ++x +         : 2 + 
    ++x + x       : 2 + 2
    ++x + x++     : 2 + 2 and x is now 3
    ++x + x++ *   : 2 + 2 *
    ++x + x++ * x : 2 + 2 * 3