What is the difference between prefix and postfix operators?

前端 未结 13 1753
天命终不由人
天命终不由人 2020-11-22 08:01

The following code prints a value of 9. Why? Here return(i++) will return a value of 11 and due to --i the value should be 10 itself, can anyone ex

13条回答
  •  深忆病人
    2020-11-22 08:44

    Let's keep this as simple as possible.

    let i = 1
    console.log('A', i)    // 1
    console.log('B', ++i)  // 2
    console.log('C', i++)  // 3
    console.log('D', i)    // 4
    

    A) Prints the value of i B) First i is incremented then the console.log is run with i as it's new value C) Console.log is run with i at its current value, then i will get incemented D) Prints the value of i

    In short if you use the pre-shorthand i.e(++i) i will get updated before the line is executed. If you use the post-shorthand i.e(i++) the current line will run as if i had not been updated yet then i gets increased so ther next time your interpreter comes accross i it will have been increrased.

提交回复
热议问题