0

Possible Duplicate:
++someVariable Vs. someVariable++ in Javascript

I am struggling to understand the increment operator. This operator increments (adds one to) its operand and returns a value. I have used it postfix with operator after operand (x++), so it returns the value before incrementing.

So if x is three, then the statement y = x++ sets y to 3 and increments x to 4

var x = 3; 
var y = x++; 

console.log(x); // 4
console.log(y); // 3

I am not understanding why y does not hold a value of 4 and is instead set to 3, and why it is that x holds a value of 4, when it was assigned a value of 3.

3
  • x++ is executed after the variable assignment. So y get the value of x which is 3. Then the value of x is increased by 1. Leaving you with x = 4 and y = 3. Commented Jan 14, 2013 at 14:30
  • From the MDN docs: "This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. [...]" ... is it clear now or are you struggling with it? Commented Jan 14, 2013 at 14:34
  • 2
    I suggest that you follow Douglas Crockford's advice and avoid the increment and decrement operators jslint.com/lint.html#inc Commented Jan 14, 2013 at 14:44

9 Answers 9

4

The post-increment operator increments after its value is taken. That's what makes it different from the pre-increment operator.

Sign up to request clarification or add additional context in comments.

Comments

2
var y = x++;

Is shorthand for these two statements (in order):

var y = x;
x = x + 1;

If you want y to equal 4 you would do:

var y = ++x;

which is short hand for:

x = x + 1;
var y = x;

Comments

2

The question has been improved by following the Alex comments.

Suppose to have a variable x, s.a. var x=3.

CASE 1 When you write:

var y = x++;

then, the following steps are done:

  1. the variable x is evaluated (x is 3);
  2. the variable x is incremented (x is 4);
  3. the result of the evaluation (happened in step (1)) is assigned to y (hence will result y=3);

CASE 2 When you write: var y = ++x;

then, the following steps are done:

  1. the variable x is incremented (x is 4);
  2. the variable x is evaluated (x is 4);
  3. the result of the evaluation (happened in step (2)) is assigned to y (hence will result y=4);

It is important to follow the operators precedence for Javascript (e.g., see more here) in this cases.

CASE 3 For sake of completeness, as observed by Alex, it is also important to recognize that if the steps provided in CASE1 are repeated on the same variable, then the variable will be incremented and then restored to the initial value, i.e. when you write:

x = x++;

then, the following steps are done:

  1. the variable x is evaluated (x is 3);
  2. the variable x is incremented (x is 4);
  3. the result of the evaluation (happened in step (1)) is assigned to x (hence will result x=3);

11 Comments

This is wrong. The increment (both post and pre) happen before the assignment. The difference between the two is wether the increment happens before or after their own evaluation.
No no, you are absolutely wrong! See this fiddle. I also updated my answer to show the same example.
Moreover, you have to notice that my answer is the same of the accepted one.
Your jsfiddle doesn't prove anything. You alert after the statement so how does this prove the increment happened after the assignment? Here is a snippet that shows x is already incremented before y is assigned a value: var x = 0; var y = ( function( c ) { console.log( x ); console.log( y ); return c; }( x++ ) ); console.log( y ); The accepted answer is as incorrect as most of the answers here.
No, the fact that y has value 3, that is the value before the post-increment prove it! In the same way, z has the value of x after that x is incremented. Moreover, consider that David Schwartz said the same I wrote: is he wrong too?
|
1

From the MDN Docs - Arithmetic Operators

++ (Increment)

The increment operator is used as follows:

var++ or ++var

This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

For example, if x is three, then the statement y = x++ sets y to 3 and increments x to 4. If x is 3, then the statement y = ++x increments x to 4 and sets y to 4.

Comments

0

The ++ after the variable is a post increment operator meaning the increment is performed after the variable is read.

See: http://en.wikipedia.org/wiki/Increment_and_decrement_operators

2 Comments

it is not incremented at the end of the statement, but immediately after evaluation of the (sub)expression
@Alex I fixed my language, does this now make sense?
0

x++ is the *post*increment operator. It's equivalent to:

 var tmp = x;
 x = x + 1;
 return tmp;

This is a leftover from the good old C days where people would love to write code like:

 while(*dest++ = *src++);

(translation: copy a memory range up to the first 0 byte). There is also a *pre*increment operator ++ x which increments first and then returns the incremented result.

Comments

0

there are two ways of increasing

var y = x++; // first make the allocation then the increasing
// and
var y = ++x; // first make the increasing then the allocation

Comments

0

The increment with x++ happens after a temporary copy of the value of x is made and the temporary copy is returned. The opposite would be ++x which is an increment and return the new value:

var x = 3;
var y = ++x; // y === 4

Quote from ECMA 5.1:

PostfixExpression : LeftHandSideExpression LeftHandSideExpression [no LineTerminator here] ++ LeftHandSideExpression [no LineTerminator here] -- 70 © Ecma International 2011
11.3.1 Postfix Increment Operator The production PostfixExpression : LeftHandSideExpression [no LineTerminator here] ++ is evaluated as follows: 1. Let lhs be the result of evaluating LeftHandSideExpression. 2. 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" 3. Let oldValue be ToNumber(GetValue(lhs)). 4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3). 5. Call PutValue(lhs, newValue). 6. Return oldValue.

7 Comments

This is wrong. The increment (both post and pre) happen before the assignment. The difference between the two is wether the increment happens before or after their own evaluation.
@Alex Isn't it about operator precedence. The assignment operator precedes or succeeds the increment operator.
Operator precedence determines the order in which operators are evaluated. The pre- and postincrement operators are evaluated in the same order. It's just that their actual evaluation differs.
@Alex Well if you can word this in a better way than me then feel free to edit the post or to post your own answer. What is the difference between "evaluation" and "actual evaluation" because you lost me there?
(Argh!) their execution differs would have been better wording. The accepted answer of the duplicate thread is pretty much perfect imho.
|
0
var y = x++; 

Means that x is incremented, and y is assigned the incremented value of x.

var y = ++x;

Means that that x is incremented, and y is assigned the pre-incremented value of x.

4 Comments

did you mean var y = ++x for the second example?
x is incremented before it is assigned to y, even in your first example. its just that x++ evaluates to the value of x before the increment.
Is that true in JS? I know it is in C# but I assumed that that would be language-dependent feature so went for the generalized explanation.
var x = 0; var y = ( function( c ) { console.log( x ); return c; }( x++ ) ); console.log( y ); // 1 0 --- True, in C and some other languages ++ is different (or even unpredictable). But there is no generalized explanation that I know of. There are simply a few different ones. None of them are right or wrong or more general than the other.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.