javascriptdebugging

How to debug non-working javascript code in a browser


This js program should display the first 100 prime numbers, but instead it crashes each and every time and I can't find the error! Could someone point me towards the best way to debug js code?! Thank you!

// initialisation of the array p holding the first 100 prime numbers
var p = [];

// set the first prime number to 2
p.push(2);

// find the first 100 prime numbers and place them in the array p
var i = 3;
while (p.length < 100) {
    var prime = true;
    loop:
    for (var item in p){
        if (i%item === 0){
            prime = false;
            break loop;
        }
    }
    if (prime)
        p.push(i);
    i = i + 2;
}

// display the first 100 prime numbers found
var i=1;
for (var item in p){
    document.writeln(i,item);
    i++;
}

Solution

  • Change:

    for (var item in p) {
    

    to:

    for (var i = 0; i < p.length; i++) {
        item = p[i];
    

    for-in iterates over the keys of an object or array, not the values.