How do you avoid an infinite loop?


#1

i just want to know so my browser doesn't crash

#2

Start with blocking...

Eg.

while () {
    break;
}

If we run this we should expect a syntax error.

SyntaxError: expected expression, got ')'

The operative word here is, 'expect'. We know the code will not run.

Adding a conditional and some indication that the loop runs...

condition = true;
while (condition) {
    console.log(condition);
    break;
}
console.log("Bye");

When we run this we get no errors and the expected output...

true
Bye

To be able to remove the break statement we need to have the condition change inside the loop, else it will crash the browser.

condition = true;
while (condition) {
    console.log(condition);
    condition = !condition;  // toggle the boolean
}
console.log("Bye");

Now we know the loop can end itself.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.