++someVariable vs. someVariable++ in JavaScript

后端 未结 6 2032
长发绾君心
长发绾君心 2020-11-22 02:02

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences b

6条回答
  •  清歌不尽
    2020-11-22 02:42

    I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.

    Lets assign 0 to x

    let x = 0;
    

    Lets start with post-increment

    console.log(x++); // Outputs 0
    

    Why?

    Lets break the x++ expression down

    x = x;
    x = x + 1;
    

    First statement returns the value of x which is 0

    And later when you use x variable anywhere, then the second statement is executed

    Second statement returns the value of this x + 1 expression which is (0 + 1) = 1

    Keep in mind the value of x at this state which is 1

    Now lets start with pre-increment

    console.log(++x); // Outputs 2
    

    Why?

    Lets break the ++x expression down

    x = x + 1;
    x = x;
    

    First statement returns the value of this x + 1 expression which is (1 + 1) = 2

    Second statement returns the value of x which is 2 so x = 2 thus it returns 2

    Hope this would help you understand what post-increment and pre-increment are!

提交回复
热议问题