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.

Community
  • 1
  • 1
user1554264
  • 1,204
  • 3
  • 22
  • 47
  • `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`. – clentfort Jan 14 '13 at 14:30
  • From the [MDN docs](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Arithmetic_Operators#.2B.2B_.28Increment.29): *"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? – Felix Kling Jan 14 '13 at 14:34
  • 2
    I suggest that you follow Douglas Crockford's advice and avoid the increment and decrement operators http://www.jslint.com/lint.html#inc – Aaron Kurtzhals Jan 14 '13 at 14:44

9 Answers9

4

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

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
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);
JeanValjean
  • 17,172
  • 23
  • 113
  • 157
  • 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 Jan 14 '13 at 21:17
  • No no, you are absolutely wrong! See [this fiddle](http://jsfiddle.net/b9fbC/5/). I also updated my answer to show the same example. – JeanValjean Jan 15 '13 at 08:19
  • Moreover, you have to notice that my answer is the same of the accepted one. – JeanValjean Jan 15 '13 at 08:38
  • 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. – Alex Jan 15 '13 at 08:52
  • 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? – JeanValjean Jan 15 '13 at 09:20
  • This question is a duplicate. Read the accepted answer from the [master question](http://stackoverflow.com/a/3469896/1339429). – JeanValjean Jan 15 '13 at 09:34
  • Oh boy. You're saying var y = x++ is executed as (1) evaluate x (2) assign to y (3) increment x; when in reality it is: (1) evaluate x (2) increment x (3) assign result of step 1 to y. The increment happens BEFORE the assignment, even if it is postincrement. This is how the ecmascript reference defines it and how it is implemented. The accepted answer from the master question is correct, yours is not. If what you are saying is true, how would you explain x = x++ not changing x? – Alex Jan 15 '13 at 10:03
  • Oooh, now I got your point! Please, consider that I never said that! I said "assigns x value to y and then increment only x."....(continue) – JeanValjean Jan 15 '13 at 10:27
  • So, in my opinion you misinterpreted that for me "assigns" means "(1) evaluate x (2) assign to y"! I never said that and also I never provided these details. Maybe my answer is not detailed, but not wrong. The output of my passages are correct! Your example `x=x++` is correct but is not the same of `var y=x++`, since you are workin' on the same variable. I have to recognize that I should improve the answer to let it more generic, but the question was on a specific problem `var x=3; var y=x++;`. Isn't it? – JeanValjean Jan 15 '13 at 10:27
  • if assigns doesn't mean it assigns, then yes, I misinterpreted your answer. – Alex Jan 15 '13 at 10:37
  • :) You won! I will correct my answer to be more clear by including your example and description. – JeanValjean Jan 15 '13 at 10:41
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;
dough
  • 714
  • 5
  • 14
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.

epascarello
  • 204,599
  • 20
  • 195
  • 236
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

CraigTeegarden
  • 8,173
  • 8
  • 38
  • 43
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.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • 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 Jan 14 '13 at 21:17
  • @Alex Isn't it about operator precedence. The assignment operator precedes or succeeds the increment operator. – Konstantin Dinev Jan 14 '13 at 21:35
  • 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 Jan 14 '13 at 21:38
  • @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? – Konstantin Dinev Jan 14 '13 at 21:45
  • (Argh!) their *execution* differs would have been better wording. The accepted answer of the duplicate thread is pretty much perfect imho. – Alex Jan 14 '13 at 21:48
  • @Alex By ECMA 5.1 what you are saying is wrong and I quote in my updated answer. The operator precedence is exactly as I infer in my answer. Point 1 in the execution is left lhs be the result of evaluating the left hand side expression and only after does the postfix ++ get evaluated. – Konstantin Dinev Jan 14 '13 at 21:54
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22723/discussion-between-alex-and-konstantin-d-infragistics) – Alex Jan 14 '13 at 22:01
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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
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
algorhythm
  • 8,530
  • 3
  • 35
  • 47
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.

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
  • did you mean `var y = ++x` for the second example? – CraigTeegarden Jan 14 '13 at 14:33
  • 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. – Alex Jan 14 '13 at 14:40
  • 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. – Levi Botelho Jan 14 '13 at 14:47
  • 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. – Alex Jan 14 '13 at 21:32