Question about a Javascript function made to check for prime numbers

Let’s be clear about what return means here:

if (15 % 2 == 0)  return false;

The condition isn’t met. 15 isn’t divisible by 2. The function doesn’t return false, but proceeds to the next step in the loop.

if (15 % 3 === 0) return false;

Now the condition is met, and the function executes the return false line (which will also terminate the whole function).

Trying that with a prime like 7:

if (7 % 2 === 0) return false; 

The if condition isn’t met, so, next step… next step… next step… until finally

if (7 % 6 === 0) return false; 

The if condition still isn’t met. And the loop is at its end. No more numbers to check. So now the last line return true will run. 7 is prime because we checked all numbers smaller than 7 in the loop, and the if condition was never met.

(notice how I say “if condition isn’t met” instead of “if statement returns false” to avoid confusion. What the function returns depends on what the if statement returns. If the if statement returns true, the function returns false. Hope your head hasn’t exploded by now.)

1 Like

Thank you, that cleared it up a lot for me.
Head was almost about to explode but I think I understand how it works now…
Thanks so much!

Yeah coding feels like a maze sometimes. Writing the steps down on paper can be a great help when it all gets tangled up.

Just wrote down the steps on paper… But there is another piece of code I have been studying and need help on. But that’ll be on another forum post haha.