Sum of all primes function question

I have a minor question about the following function on StackOverflow.com stackoverflow prime number function. Given as reference by freeCodecamp to help solve this algorithm Sum of all Primes. Can any one please explain why number 2 is true when passed into this function isPrime.

function isPrime(num) {
    if(num < 2) return false;
    for (var i = 2; i < num; i++) {
        if(num%i==0)
            return false;
    }
    return true;
}

How can number 2(num) be true(prime) when the for loop starts from 2 . And 2 modulus(%) 2 equals 0.
It should return false?.

This function looks correct to me.
Firstly, 2 is a prime number.
The reason that the function returns true for 2 is that the condition i < num is false, so the for loop doesn’t run for that value.

Thank you. This was puzzling me to now end. It seems obvious now with your precise answer. I cannot believe I missed that i is not smaller than num(2) it does not run the for loop for integer 2.

1 Like