# What is if (isPrime(i)) referencing? and why do for loops no longer make sense?

Tell us what’s happening:
I understand that the helper function only returns a value of prime for sum to use. But is if(isPrime(i)) on line 18 referencing i of the helper function? I think I just don’t understand how for loops work…
The second question (which made complete sense up until now) is based on my iteration() function. A fundamental understanding of both referencing helper functions and for loops would really solidify my understanding of javascript ``````
function sumPrimes(num) {
// Helper function to check primes
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
//square rooting num so that each iteration of i, which is two, is balanced out by the square root(for example, sqrt of 10 is 3, so i is 6, 10 % 6 is 4, which returns true)?
if (num % i == 0)
//this returns false if the remainder of num based on the square root of i is a composite
return false;
}
return true;
}

// Check all numbers for prime
let sum = 0;
for (let i = 2; i <= num; i++) {
//we use 10 again, which means i = 20
if (isPrime(i))
//we then put in 20 into isPrime(20) which based on the for loop, returns true? then the answer is 21 if I pass in 10 as num? HALP
sum += i;
}
return sum;
}

console.log(sumPrimes(10))

function iteration(int){
let sumnum = 0;
for(let i = 2; i < int; i++)
{
sumnum += i
}
return sumnum;
}

console.log(iteration(4))
/*shouldn't it be 6 because the for loop only iterates 3 times (exluding the int value 4 itself because not <=) and thus sumnum is 3 iterations of i added together, and since i is 2 we return 6.
but console.log() returns 5? It gets even weirder if I increase i in iteration() to 3, and the console logs a lower number of 3. */

``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36`.

Challenge: Sum All Primes

No. The `i` inside of the helper function is in the scope of the helper function. It can’t be accessed outside of the helper function.

The `i` in `isPrime(i)` refers to the `i` in this scope, this for loop over every number from 2 to `num`.

The idea is to read the function name literally. Loop for `i` from 2 to `num`. If `i` is prime, then add `i` to the `sum`.

The body if the `isPrime` is separate from the use of the function.

2 Likes

Summing from 2 to 4, excluding 4 is 2+3=5. I’m not sure where 6 comes from? Did you start adding at 1 perhaps?

I’m such an idiot. I kept thinking that since I i = 2, i++ means increment it at 2 each time, not by one starting from 2. I also understand why increasing i to 3 decreases the value because if it goes higher than num which is 4 the for loop stops.

Oh, we’ve all misread code from time to time.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.