Pranav Ghate
Pranav Ghate

Reputation: 57

Why is there a potential infinite loop in my JavaScript Code?

I wish to find the sum of all prime numbers between range defined from 1 to N. The code gives an infinite loop when I call the sumPrimes function with a value of 3. I have debugged the code and found out that it does that only for the number 3. It does not do so for any other numbers above 2.

JavaScript:

function sumPrimes(num) { 
    var sum=0;
    for (i = 2; i <= num; i++) {
        if (checkPrime(i)) {
            sum += i;
        }
    }

    return sum;
}

function checkPrime(num) {
    for (i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) {
            return false;
        }
    }

    return true;
}

Upvotes: 3

Views: 235

Answers (2)

A.Baudouin
A.Baudouin

Reputation: 2925

Because you have to declare i with var : it will make it local to the function.

for (var i = 2; i <= num...

otherwise the two functions use the same global variable.

If you want to avoid this kind of bug, you should use strict mode. JavaScript Use Strict

You just have to put "use strict"; at the top of your .js file.

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179046

You haven't declared a scope for i, which means that both loops will keep resetting the value of i in global scope, causing the loop to continue endlessly.

Add var i to the top of both functions and the problem will disappear.

Upvotes: 1

Related Questions