Search code examples
javascriptwhile-loopinfinite-loop

How do I stop an infinite loop from occurring while getting user input?


I'm a newbie writing a program that continues to ask the user for a number until the entered number is less than or equal to 100. I keep ending up in an infinite loop and I'm unsure of how to add the correct conditions to end the loop.

let num;

while (!(num === 100 && num < 99)) {     // infinite loop
    num = Number(prompt("Enter a number: "));
    console.log(num);
}

I want to exit the loop when the user enters a number less than or equal to 100.


Solution

  • To resolve this issue use either

    !(num === 100 || num < 100)  or
    !(num <= 100)
    

    Issue: Num can never be both equal to 100 and less than 99 , so it will be false always and so while condition is true always

    let num; 
    while (!(num <= 100)) { //or !(num === 100 || num < 100)
      num = Number(prompt("Enter a number: ")); 
      console.log(num); 
    }