How does this for loop work? It doesn't make sense to me.
for ( ; i < length; i++ ) {
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?');
for (;;)
, that brings back memories from before I realized while (true)
was more legible (for some reason, I was introduced to for (;;)
as the canonical way to create an infinite loop)...
while(true)
is for sure easier to read. Casting with !!
or ~~
is also fun..
Apr 24, 2012 at 4:24
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.
for
loop, and there just happens to be no initialization step required, then I see nothing wrong with using that form. The real difference arises if there's a continue
within the loop body -- the for
form increments, but the while
form does not. I've edited my answer to reflect this, thanks.
i++
part was also omitted, eg for (;i<length;)
My questions is why would that be prefered over writing a simple while (i<length)
? I have seen this contraption in the jquery library for example.