Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop missing middle part: error or advanced?

I am in the process of debugging another developer's Javascript for a project at work.

I am probably a mid-level Javascript developer on a good day and I've come across a for loop that appears broken:

for(i = 0; ; i++)

Can anyone tell me if this is indeed a mistake or if in some instances this is a perfectly valid way to do Advanced things?

like image 777
timmackay Avatar asked Jun 20 '12 04:06

timmackay


People also ask

What are the different kinds of loops in JavaScript?

JavaScript supports different kinds of loops: for - loops through a block of code a number of times for/in - loops through the properties of an object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true

How do you stop a JavaScript loop?

In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process. Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by while. For instance, a shorter way to write while (i != 0) is while (i):

What does the JavaScript exception “missing ) after condition” mean?

The JavaScript exception "missing ) after condition" occurs when there is an error with how an if condition is written. It must appear in parenthesis after the if keyword. SyntaxError: missing ) after condition (Firefox) SyntaxError: Unexpected token ' {'. Expected ')' to end an 'if' condition. (Safari) What went wrong?

Can we specify initializer before starting for loop in JavaScript?

You can specify initializer before starting for loop. The condition and increment statements can be included inside the block. Learn about while loop in the next section. JavaScript for loop is used to execute code repeatedly.


1 Answers

It's OK and perfectly legal. Any of the three slots in a for statement can be left empty. Except for the condition that i added, it's logically the same as this:

i = 0;
while (true) {
    // other code here
    if (some condition) {
        break;
    }
    i++;
}

It will be an infinite loop unless there is a test somewhere in the loop that issues a break statement under some conditions to stop the loop (I added a sample test to my code example).

like image 187
jfriend00 Avatar answered Nov 15 '22 16:11

jfriend00