Infinite loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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!"); ____________ } }

25th Jul 2017, 7:56 PM
Manik Tafralian
Manik Tafralian - avatar
2 Answers
+ 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; }
25th Jul 2017, 8:02 PM
Rrestoring faith
Rrestoring faith - avatar
+ 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.
25th Jul 2017, 8:04 PM
josh mizzi
josh mizzi - avatar