skip to Main Content

Why is there a big diffrence in using for loop with and without constraints.

With condition
for(var i = 3; i >= 0; i--) { console.log(i); }

outputs
3
2
1
0

Without condition
for(var i = 3; i--;) { console.log(i); }

outputs
2
1
0

Why does the one without condition skip the first iteration and also stop at 0.

If you use no condition but add one instead of subtract it will result in an infinite loop

2

Answers


  1. The second one does have a condition: i--. The modification to i in the condition is a side effect.

    The condition runs before the log statement (instead of after it) so it doesn’t log 3 because i changed too soon.

    0 is a false value so when i-- evaluates as 0 the condition no longer matches.

    Login or Signup to reply.
  2. for ([initialization]; [condition]; [final-expression])
    

    In your case, the final-expression is not used.
    The condition is i-- and it will stop when this is falsy, which means when i-- = 0

    And the condition is executed every time before each itteration. Thus skipping 3.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search