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?
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
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):
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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With