Why does this loop crash?

Instead of giving you the answer, I'm going to walk you through how I figured it out to hopefully get you in the right mindset.

First, an infinite loop means your condition is always true. Looking at your loop, the condition is answer === 0. This means that for some reason, answer is always 0 and never changes.

Now let's look at where you used answer. You used it in exactly two other places: Once to initialize answer with a value of 0, and once to make it equal to biggestPrime in your if() statement.

Now let's look at the if() statement where it's supposed to change the value of answer. The condition is if start%biggestPrime ===0. This means this conditional statement is always false throughout your loop. Why?

Let's look at both start and biggestPrime now. Start is used exactly once, outside your loop when you declare it with a value I am not going to type out because I'm lazy. Likewise, you use biggestPrime exactly two times: Once to initialize it with a value, and once to make it equal to -1 in your else() statement.

Now let's look at your else statement. Since your if() statement always fails, then the else() statement must be called. This means after the first iteration of the loop, biggestPrime is changed to -1.

Now we go back to start. Remember when I said start is used exactly once at the initialization? This means that you never change your value of it again. So throughout your entire loop, you're depending on answer changing by if start % biggestPrime === 0. However, start never changes and biggestPrime changes to -1 after the first run, so you're basically stuck because you keep comparing the exact same values of start % biggestPrime infinitely.

And that's why your loop is infinite: You're repeatedly using the exact same values for two of your variables and that's causing your third to never change as well.

/r/learnprogramming Thread