Assessment wanted for Loops 1, Loops 2 and Loops 3 skill tests
I have a question about the Loops 3 skill test. It contains this function:
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}
return true;
}
Shouldn’t this function use an if else
statement instead?
What would you put into the else
part?
The return true;
part can’t be there, because this should only be executed when the loop finishes all rounds without finding a single number that divides num
without a remainder.
The return
statement doesn’t just leave the loop, it leaves the whole function.
So as the code is written the return true;
statement has to be placed just before the final closing curly brace so that the result of the isPrime()
function will be saved in the global scope. Because the return false;
statement leaves only the for()
loop but the return true;
statement leaves the isPrime()
function. Is this correct?
No, not quite.
Both return
statements will leave the whole function. It doesn’t matter if return
is inside a loop or an if
statement or similar construct. return
will always exit the function and gives its value to whoever called the function.
In our case it’s the if
statement in the while loop that calls the function. The loop runs about 500 times and therefore isPrime()
gets called the same amount. The return values of this function don’t get saved anywhere. The function will just either return true
or false
depending on the parameter value i
and then the if
statment uses this information to either write something into para.textContent
or not.
So let’s say I write the code like this:
const para = document.createElement('p');
document.body.appendChild(para);
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
} else {
return true;
}
}
}
for(let i = 500; i >= 2; i--) {
if(isPrime(i)) {
para.textContent += `${i} `;
}
}
If I understand you correctly, the reason that this code is incorrectly written is as follows:
First 500 will be passed into the isPrime()
function. The remainder of 500 and 2 is 0, so isPrime()
will immediately return false
without completing the loops for numbers 3 through 499. Then 499 will be passed into isPrime()
and isPrime()
will immediately return true
because the rest of the numbers 3 through 498 have not been evaluated. In the end all of the odd numbers will be printed.
So return true;
has to be placed outside of the for()
statement in isPrime()
in order for the loops for numbers 2 through < num
to fully run there course and thereby return only the numbers for which a number between 2
and < num
return true.
Is this correct?
Yes, you got it.