Unexpected result of increments sum

Viewed 50

Good afternoon, please explain why, when waiting for 3, 4 is output to the console.

let x = 1;
console.log (x++ + ++x) // 4

At first, I thought that the priority of operations, but then why in such an example outputs 8, and not 6 for example?

let x = 1;
console.log (x++ + ++x + ++x) // 8

Sorry, if this question is duplicated, but I can't find any about this question.

2 Answers

For the first example:

let x = 1;
console.log (x++ + ++x) // 4

  1. x++ returns the value of x (1) and increments it afterward. x is now 2. (This is postfix increment.)
  2. ++x increments the value of x and returns it, which is 3 (2 + 1). (This is prefix increment.)
  3. 1 + 3 = 4

See Increment Operator.

x++ or x-- is first use then update.
++x or --x is first update then use.

update means update the value of the variable x.

Related