user2512058
user2512058

Reputation: 1

First 100 primes javascript, why do I get undefined after my array of primes?

I get the 100 primes printed, but I also get undefined at the end. Why would that be?

function HundoPrimeNumbers() {
    var primes = [];

    function isPrime(n) {
        if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) return false;
        var m = Math.sqrt(n);
        for (var i = 2; i <= m; i++) if (n % i == 0) return false;
        primes.push(n);
    }

    var n = 0
    while (primes.length < 100) {
        isPrime(n);
        n++;
    }
    console.log(primes.join());
}

console.log(HundoPrimeNumbers());

Upvotes: 0

Views: 821

Answers (2)

Chubby Boy
Chubby Boy

Reputation: 31072

undefined is the return value of console.log()

Upvotes: 0

Claudiu
Claudiu

Reputation: 229521

You are logging the result of HundoPrimeNumbers:

console.log(HundoPrimeNumbers()); 

HundoPrimeNumbers does not have a return statement. When a function doesn't have a return statement, or returns without a value, like return;, it actually ends up returning undefined. This then gets logged to the console.

Solution: call it like this:

HundoPrimeNumbers();

Upvotes: 3

Related Questions