@timandes this is an interesting one. The reason we don’t put the iterator at the bottom of the block is that, earlier on in the block, we continue
the loop if the number is not a prime number. If we don’t decrement the value of i
first, this would result in us continually running the isPrime()
function on a non-prime number, then continuing, then doing it again, forever. An infinite loop, in effect.
So therefore this fixes that:
while(i > 2) {
i--;
if(!isPrime(i)) {
continue;
}
para.textContent += `${i} `;
}
I’ve changed the exit condition to > 2. Because the lowest prime number is 2 — 1 and 0 don’t count as prime numbers! I’ve updated this in the question already.
Now, strictly speaking, the above answer is still a bit shonky, as we are reducing the value of i
immediately before we actually do anything to it, so therefore 500 gets skipped completely. This doesn’t matter for the purposes of this code, because we know 500 is not a prime number, but it’s not a very good practice.
In addition, you end up outputting 1 if you do i >= 2
, which is the range we are told to work between, so therefore you have to end up putting i > 2
. to make it work. But this is not very intuitive.
So therefore a better answer would be this:
while(i >= 2) {
if(!isPrime(i)) {
i--;
continue;
}
para.textContent += `${i} `;
i--;
}
It is difficult to write it more elegantly, because in the if block, the i--
has to come before the continue
, otherwise we break out of the loop iteration and i--
never runs.