Peter Carter
Peter Carter

Reputation: 2728

Javascript for loop producing unexpected results

I have written the following loop:

for (i = 10; i--; i > 5) {
  console.log(i);
}

Which outputs this to the console:

9
8
7
6
5
4
3
2
1
0

Can anyone tell me why it's doing this?

I had a look and it seems like it's just a simple matter of having to increment using the third parameter of the for loop, rather than the second, but I'm fascinated as to the digits logged to the console. Can anyone give me a simple explanation of why it outputs the numbers it does?

Upvotes: 1

Views: 116

Answers (3)

Ian
Ian

Reputation: 30813

The for loop has this structure:

for (initial condition ; termination condition ; incremental condition)

In your for loop, the termination and incremental condition are swapped (!):

for (i = 10; i--; i > 5)

That is:

initial condition: i = 10
termination condition: i-- !!!
incremental condition: i > 5 ??? Does not do incremental

Then, as long as the termination condition returns true (that is, when i > 0), the loop continues.

And since i, having an initial value of 10, will only become 0 after the i-- is executed 10 times, the result returned was:

9 8 7 6 5 4 3 2 1 0

Totaling 10 loops.

Upvotes: 4

zb'
zb'

Reputation: 8049

The loop did not finish when you expected because Boolean(i--) is false only if i == 0; in short, you misplace compare and action in the loop.

Upvotes: 1

CoR
CoR

Reputation: 3914

Question is now corrected so ignore: Firstly, you are wrong - it does not produce the output you indicated :). Instead it produces the following:

for (i = 11; i--; i > 5) {console.log(i);}
// 10 9 8 7 6 5 4 3 2 1 0

It starts with 10, not with 9 :).

Secondly, you are not allowed to change the order of statements in the for block. Instead, you must specify them as shown:

for (i = 11; i > 5; i--) { console.log(i); }
// 11 10 9 8 7 6

Third (and most important):

  1. You put a starting value in i; whatever value you want or need.
  2. Then you create the condition which checks whether to continue looping.
  3. The third statement is usually used to increment or decrement i.

Upvotes: -1

Related Questions