Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this for loop work? for ( ; i < length; i++ )

How does this for loop work? It doesn't make sense to me.

for ( ; i < length; i++ ) {
like image 516
Jackie Chan Avatar asked Apr 24 '12 04:04

Jackie Chan


2 Answers

The loop will simply repeat as long as i is less than length. It simply assumes i is already declared elsewhere.

Actually, all parts within a for loop construct are optional. For example, this is a perfectly valid way to create an endless loop:

​for(;;) window.alert('Are you sick of alerts yet?');​​​​​​​​​
like image 110
Mike Christensen Avatar answered Oct 16 '22 21:10

Mike Christensen


It's a regular for loop that does nothing at all in the initialization step.

This is equivalent to writing:

;
while (i < length) {
    // ...
    i++;
}

except if there's a continue in the ... body, in which case the for loop would execute the i++ before re-evaluating the condition, and the while loop would not.

like image 43
Cameron Avatar answered Oct 16 '22 20:10

Cameron