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?
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?
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);
a
is set to 1
a++
returns 1, and then a
is incremented to 2
(but we don't do anything with it at this point)++a
increments a
and returns 3console.log(1 + 3)
with the 1
coming from step 1 and the 3
coming from step 3.what is the sequence of this
In pseudo spec language:
a++ + ++a
)
lval
be the result of evaluating the left operand (a++
)
a
and assign it to oldValue
. (1
)newValue
be oldValue + 1
.newValue
to a
. (a == 2
)oldValue
. (1
)rval
be the result of evaluating the right operand (++a
)
a
and assign it to oldValue
. (2
)newValue
be oldValue + 1
.newValue
to a
. (a == 3
)newValue
. (3
)lval + rval
. (1 + 3
)4
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..