9

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

for ( ; i < length; i++ ) {

2 Answers 2

15

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?');​​​​​​​​​
3
  • 1
    +1 for 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)...
    – Cameron
    Apr 24, 2012 at 4:18
  • Yea, JavaScript is a unique language in that these sorts of hacky-ish shortcuts are somewhat encouraged just to save bytes over the wire. Otherwise, while(true) is for sure easier to read. Casting with !! or ~~ is also fun.. Apr 24, 2012 at 4:24
  • Hah, but I was actually learning C++ at the time (first programming language), not JavaScript! ;-)
    – Cameron
    Apr 24, 2012 at 4:27
9

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.

4
  • So why would one prefer writing this over a simple while loop ?
    – nl-x
    Jul 23, 2014 at 10:08
  • 1
    @nl-x: Good point. It's more compact, though slightly less readable; however, if the intent is to have a normal 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.
    – Cameron
    Jul 23, 2014 at 11:21
  • Sorry, I was not looking clearly. I thought the 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.
    – nl-x
    Jul 23, 2014 at 11:33
  • @nl-x: Hmm, beats me!
    – Cameron
    Jul 23, 2014 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.