Hi all,
I was exploring for
loops, and the use of if
statements within them, and I’m unclear about how they actually execute. Here’s a function that finds whether a number is prime:
function isPrime(num) {
for (let i = 2; i < num; i++)
if (num % i === 0) {
return false;
return num > 1;
};
I understand generally what’s happening. isPrime(12);
for example, would divide the number 12 starting with 2, and increasing by one until 11. If 12 is divisible by that number, it will return false
. If it isn’t, it will return true
if 12 is greater than 1.
My understanding, however, is that the for
loop would iterate through until i < num
. So, while 12 % 2
will return false
, 12 % 11
will not. So why does the statement return false? Or why doesn’t the statement return a multiple false
and true
values? Does it just stop if the if
statement’s condition is met?
I clearly don’t have a firm understanding of how this works, specifically.
Thanks for any explanation that can help!
Hi, welcome to the forums!
There’s a couple of points for clarification here:
 “would divide the number 12 starting with 2”  The % (modulus operator) is not one that deals with division. Nothing is being divided in this code

12 % 2
will return false
 12 % 2
evaluates to 0. So 12 % 2 === 0
evaluates to true
.
 The modulus operator calculates the remainder after division. So 6%5=1, 6%4=2 etc.
For the code itself, unwrapping from the inside out, there’s a couple of issues. For one there’s two return statements in one code block
if (num % i === 0) {
return false;
return num > 1;
}
Unlike python, indentation won’t matter here, and the first return will be the one that always triggers.
As for the second return statement, you don’t want it to be in your forloop. You should explicitly bracket the loop so you leave it out. Otherwise it won’t cycle through your list and properly filter the prime number.
if (num % i === 0) {
return false;
}
return num > 1;
You’ll notice that with this logic, if the number is not even, it will return num > 1
.
return
stops the running of the function if I remember correctly. So that’s why.
Thanks for catching the errors in the code, and clarifying the modulus operator for me. Makes sense.
Once the return statement is expressed, does the for loop stop?
Ah! This would make sense. Thank you!
No problem!
Return statements, once run, end the function, not just the loop (not going to mention recursion, but technically it’s true with recursion as well).
@blogmaster63629 You can also run test code like this, it will tell you how it’s evaluating the condition for every i:
function isPrime(num) {
for (let i = 2; i < num; i++){
console.log(num % i === 0)
}
};
1 Like