javascriptincrementpost-incrementpre-incrementunary-operator

++someVariable vs. someVariable++ in JavaScript


In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?


Solution

  • Same as in other languages:

    Now when used as a standalone statement, they mean the same thing:

    x++;
    ++x;
    

    The difference comes when you use the value of the expression elsewhere. For example:

    x = 0;
    y = array[x++]; // This will get array[0]
    
    x = 0;
    y = array[++x]; // This will get array[1]