DR01D
DR01D

Reputation: 1365

Removing all statements from the top line of a for loop

Basic mechanics question. In the for loop below I moved the first and 3rd loop statements from their normal position. var i=1 is above the loop and i++ is positioned inside the loop. Everything runs fine. However I've read that a for loop can also run fine with the 2nd statement "i > 10" removed. Where can the second statement sit besides it's default position inside the parenthesis? Would the for loop look like for (;;;) ?

var i=1;
for (; i > 10;) {
    document.getElementById("test").innerHTML += i + "<br>";
    i++;
}

Upvotes: 0

Views: 37

Answers (2)

kidwon
kidwon

Reputation: 4524

Yes indeed

var i = 1;
for (;;) {
  if(i > 10) break;
  i++;
}

Upvotes: 3

user2345
user2345

Reputation: 3227

A for loop with no parameter would look like this: for(;;).

It is basically equal to while(true), therefore it will be run infinitely or stop if the keyword break is used.

You can try this out:

for(;;) {
    alert("infinite loop");
}

You will see that the alerts do not stop.

Upvotes: 3

Related Questions