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!