Search code examples
javascriptinfinite-loop

Why does this javaScript code create an infinite loop


let i = 500;
do {
    if (isPrime(i) === false) {
        continue;
    } else {
        para.textContent += i + ', ';
    }
    i--;
} while (i >= 2);

and it works well if I moved the (i--) to the start of the loop.


Solution

  • Your loop keeps iterating at -

    if (isPrime(i) === false) {  //this condition will be true and code keeps looping because you never increment i
        continue;
    }
    

    But, in your code where you declare i-- at the beginning, i will keep decreasing no matter what. So the first one will run succesfully as expected, while in the second program, the execution will never go beyond the first if() condition.