# Why does this become an infinite loop?

This is apparently an infinite loop. I believe this is because I’m using a loose comparison in the while loop instead of strict. But I’m still confused by it. Wouldn’t a loose comparison then be more likely to be true? How are the 2 variables never equal in this example?

``````const target = Math.floor(Math.random() * 10);
let guess = Math.floor(Math.random() * 10);

while (guess != target) {
console.log(guess);
guess = Math.floor(Math.random() * 10);
}
console.log(`guess: \${guess} target: \${target}`);
``````

Whether strict or loose, since you are comparing two randomly generated whole numbers, the chance of the two being equal is very low.

1 Like

But is only between 1-10, and even if the chances are low, that doesn’t explain why the resulting loop is infinite?.. (which would imply that they are never equal)

What do you mean by the loop is being infinite?

1 Like

It went on infinitely and and the Codepen console gave me the alert “Only the last 10 lines are being displayed” before it stopped it.

1 Like

I had a similar experience with codepen. I wrote an inefficient code one time because i didn’t know how to do it better using a JS library. The code ran in my browser but when i transferred it to codepen, it failed to run. I realized it was because there were many loop iterations some of which were super nested. That condition will evaluate to false but it might happen after many iterations(in some instances). Try it in the browser you will be surprised.

2 Likes

Thanks but when I use the strict operator !== it solves it quickly (it’s only guessing between 1 and 10 so it’s not really that demanding). So if I use strict !== it solves it quickly but if I use loose != it goes on infinitely.

1 Like

It must be a feature of Codepen. I have also tried it just the way you posted it, in VS code. It ran very fast.

1 Like

It’s probably a badly implemented infinite loop protection?

When I run the code on my chrome developer tools it logs at most 30 values before they’re both equal and an average of 10 so IDK why it would deem it as infinite.

1 Like