Reputation: 8559
Here's a test situation for using the unary operator "++":
var j = 0 ;
console.log(j);
j = j++;
console.log(j);
For this, the output is:
0
0
Since the ++ operator's position is at the back of the operand, so its precedence is lower than the assignment's precedence, I would expect "j" to first receive the value of itself (i.e.0), but then be incremented. So why is the second console.log(j)
call still showing "0"?
Just to be clear, I know that the solutions are:
// 1)
j++;
// 2)
++j;
// 3)
j += 1;
// 4)
j = ++j;
But I need to know why the increment step is not conducted in this specific scenario, NOT how to fix it!
Upvotes: 24
Views: 2230
Reputation: 1
j = j++
means assign RHS value first to LHS and then increment RHS by 1. On the other hand, j = ++j
means increment RHS by 1 and then assign it to LHS
Upvotes: 0
Reputation: 832
Where the ++ is lets you know what value you are going to get from it at that moment
++j; // increment the value and then give it to me.
j++; // give me the value and then increment it.
so you were saying
j = j++;
set j to the value of j before it was incremented.
Upvotes: 2
Reputation: 385114
This is an unintuitive (but not "weird"!) behaviour when using post-increment.
The statement j = j++
does this:
foo() = j++
j
(0), and remember it as the result;j
(to get 1);j
(0).The result is a no-op.
The key here is that the entire RHS is evaluated and the post-increment performed, before the final assignment.
http://www.ecma-international.org/ecma-262/5.1/#sec-11.3.1
http://www.ecma-international.org/ecma-262/5.1/#sec-11.13.1
Upvotes: 52
Reputation: 239453
According to the ECMA Specifications for Postfix Increment Operator,
- Let lhs be the result of evaluating LeftHandSideExpression.
- Throw a SyntaxError exception if the following conditions are all true:
- Type(lhs) is Reference is true
- IsStrictReference(lhs) is true
- Type(GetBase(lhs)) is Environment Record
- GetReferencedName(lhs) is either "eval" or "arguments"
- Let oldValue be ToNumber(GetValue(lhs)).
- Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).
- Call PutValue(lhs, newValue).
- Return oldValue.
So, it is clear that the new value is first set on the lhs
(in this case j
) and the the old value is returned as the result of the expression, which is again set back in j
. So, the value doesn't change.
Upvotes: 10
Reputation: 4443
j++ means at first assign,then increment
++j means at first increment,then assign
So,
var j = 0 ;
console.log(j);
j = ++j;
console.log(j);
0
1
Upvotes: -3