Barry G
Barry G

Reputation: 221

Javascript code is running out of memory

When I run the below code it crashes browsers or tells me the process is out of memory. I believe I made a mistake. What is the problem with the below code:

var primes = new Array();
var nonprimes = new Array();

var factor = function(n){
    for (var i = n; n > 1; i--)
    {
        if (n%i === 0 || n !== i){
            primes.push(i);
        }else{nonprimes.push(i);}
    }
}
factor(2);
console.log(primes);

Upvotes: 1

Views: 332

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

You're decreasing i but checking if n > 1 .

Essentially, you've created an infinite loop because you never decrease the value of n. The conditions within loops allow execution until they evaluate to false. In your example, the condition clause of the for loop will always evaluate to true and the loop will continue forever.

Consider:

for (var i = n; i > 1; i--){

Upvotes: 8

SLaks
SLaks

Reputation: 887433

Your loop will keep running until n > 1 becomes false, but n never changes.

Upvotes: 2

Related Questions