0
Infinite loop
Can someone explain why this piece of code is considered an infinite loop and how it shall be corrected ? var check = true; var loopCheck = function(check){ while(check){ console.log("Looped once!"); ____________ } }
2 Réponses
+ 4
The loop continues until the condition is false.
while(check){
...log("Stuff");
}
check is true!
So, that loop is infinite since the condition is always true.
We can stop the loop a couple ways.
For one, since we're using a variable we can make check false.
while(check){
...log("Stuff");
check = !check; // can also write false
}
Or, we can use a break; to exit the loop.
while(check){
..log("stuff");
break;
}
+ 2
The while loop continues to loop while the condition passed to it returns true. As you have not defined a condition in which check is false and you have set it to true by defult, check will always return true and thus the loop will never end.