-2

I'm trying to solve this magic in js:

var a = 1;
console.log(a++ + ++a);

It returns 4 and I can understand that it's 1+3 but what is the sequence of this?

Vadym
  • 548
  • 2
  • 8
  • 21
  • 4
    If you understand what post-increment and pre-increment operators do, it becomes pretty obvious. You just need to read the docs and the knowledge that code is executed from left to right. – Sebastian Simon Sep 26 '16 at 19:30
  • I do yet it doesn't seem obvious. Can you just describe it like 1)... 2)... 3)... in your answer? – Vadym Sep 26 '16 at 19:31
  • 2
    @Jonasw What does `2 + 2` have to do with that? – Sebastian Simon Sep 26 '16 at 19:34
  • 2
    If you see code like this in real life, then it was written by a horrible person. There are good reasons to use `++a` or `a++` depending on the scenario, but having 5 plus signs in a row for any reason is a bad idea for readability, and is just asking for a typo. – Joe Enos Sep 26 '16 at 19:36

3 Answers3

5

a++ means return the value before incrementing

++a means returns the value after incrementing

So to break down your example:

var a = 1;
console.log(a++ + ++a);
  1. a is set to 1
  2. a++ returns 1, and then a is incremented to 2 (but we don't do anything with it at this point)
  3. ++a increments a and returns 3
  4. Then altogether we have console.log(1 + 3) with the 1 coming from step 1 and the 3 coming from step 3.
j08691
  • 204,283
  • 31
  • 260
  • 272
3

what is the sequence of this

In pseudo spec language:

  1. Evaluate addition (a++ + ++a)
    1. Let lval be the result of evaluating the left operand (a++)
      1. Get the value of a and assign it to oldValue. (1)
      2. Let newValue be oldValue + 1.
      3. Assign newValue to a. (a == 2)
      4. Return oldValue. (1)
    2. Let rval be the result of evaluating the right operand (++a)
      1. Get the value of a and assign it to oldValue. (2)
      2. Let newValue be oldValue + 1.
      3. Assign newValue to a. (a == 3)
      4. Return newValue. (3)
    3. Return lval + rval. (1 + 3)
  2. Result: 4
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

To go into a bit more detail on what Xufox was saying in the comments section:

++a first increments the value of a and then returns an lvalue referring to a, so if the value of a is used then it will be the incremented value.

a++ first returns an rvalue whose value is a, that is, the old value, and then increments a at an unspecified time before the next full-expression (i.e., "before the semicolon").

Postfix increment has higher precedence than prefix increment.

This helped me a lot back in the day and it should help you too..

http://en.cppreference.com/w/cpp/language/operator_incdec

Community
  • 1
  • 1
Fadi
  • 1,329
  • 7
  • 22
  • 40