3

In Javascript, I'm having trouble understanding why these two sets of code provide different results:

for (var i = 0, a = []; i++ < 9;) {a.push(i);}

After running this code, the variable a is the following: [1, 2, 3, 4, 5, 6, 7, 8, 9].

However, this code returns something else:

for (var i = 0, a = []; i < 9; i++) {a.push(i);}

Instead, the variable a is the following after running this code: [0, 1, 2, 3, 4, 5, 6, 7, 8]

So, the major question: Why is this the case?

Thanks for any answers that explain this difference.

  • In the first case, the increment happens before the push and after the check for < 9. Hence, you get numbers from 1 to 9. In the second code, the value of i is only incremented after the first run and the check for < 9 is done after the increment. – Chetter Hummin Mar 06 '13 at 05:55
  • You can look at an explnation of the for loop at http://www.w3schools.com/js/js_loop_for.asp – Chetter Hummin Mar 06 '13 at 06:02

1 Answers1

2

It's just the order in which the for loop operations take place. The three expressions are evaluated:

  for (before the loop starts;                   // initialization 
       before each iteration of the loop;        // loop condition
       at the end of each iteration of the loop) // loop increment

That makes your i++ get run at different times relative to the loop body and explains the results you see.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Thanks, I understand this now. Does this mean that what is returned by i++ is passed to the next condition, making the difference between ++i and i++ when it is in the increment area? – Qantas 94 Heavy Mar 06 '13 at 06:02
  • I'm not really sure I understand that question. Are you asking about the difference between the pre-increment and post-increment operators? – Carl Norum Mar 06 '13 at 06:04
  • OK, let me explain. Take a look at this example: `i=0;i++; i` It will always return 1, regardless of whether it is `i++` or `++i`. However, for this code: `i=0; i++`, it will return 0. – Qantas 94 Heavy Mar 06 '13 at 06:19
  • Yes, all of that is expected. I'm still not really sure what you're asking, though. `i` is `1` after both of those sequences, it's just that the post-increment operator returns the value before doing the increment. – Carl Norum Mar 06 '13 at 15:55