HELP NEEDED! Sum All Primes

Tell us what’s happening:
Can someone tell me what is wrong with my code?
So, what I’ve tried is this -
Next value will keep increasing by 1 until the given num. Now, only if the next value is a prime number i.e divisible by itself or by 1, the curr value will change to the next value. So, in this way, the curr value will always be a prime number. Thus, I can just add the curr value and sum and save it in sum.

I’m getting 27 when I pass 7 as the num, which is incorrect.

Your code so far


function sumPrimes(num) {
  var prev = 0;
  var curr = 1;
  var next = 2;
  var sum = 0;
  
  while (next <= num) {
    if (next % next == 0 && next % 1 == 0) {
      prev = curr;
      curr = next; 
      sum += curr;
    }
    next++;
  }
  return sum;
}

sumPrimes(7);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes

The definition of a prime number is that it needs to be divisible ONLY by itself and 1.

What your code is doing is checking if a number is divisible by itself and 1, but does not check anything else. This will always evaluate to true no matter what since all numbers are divisible by itself and 1. So when you run your code, you end up summing every single number from 2 through 7. 2+3+4+5+6+7 = 27.

What you are missing is a check to do the modulo on other numbers.
For example, 4 is divisible by itself and 1. So 4%4 == 0 and 4%1 == 0 both evaluate to true. However, 4%2 == 0 is also true - and by definition this disqualifies 4 as a prime number. But your code never tries to evaluate 4%2 to disqualify it as a prime number. A similar case occurs for 6, which is divisible by 2 and 3 but your code does not check those cases.

Yup understood. Thanks for clearing it up!