Ad

Using Continue In A While Loop In Javascript

- 1 answer

Please help me to find out my mistake(s) in this code.

var  numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;

while (i < numbers.length){
    if (numbers[i] >70){
        continue;
    }
    console.log(numbers[i])
    i++;
}

I want to get output

12
34
23
8 
48

But the code shows output:

12
34
23

and the run doesn't stop.

Ad

Answer

You have an infinite loop, because if numbers[i] > 70 it's not increasing i, so the next loop it's checking that same condition again without an incremented i value. There are multiple ways to fix this, but one option is to output the value when numbers[i] <= 70, and always increment i.

var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;

while (i < numbers.length){
    if (numbers[i] <= 70){
        console.log(numbers[i]);
    }
    
    i++;
}

Another option would be a different loop:

var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;

for(i = 0; i < numbers.length; i++) {
    if (numbers[i] > 70){
       continue;
    }
    
    console.log(numbers[i]);
}

Or a simpler way:

var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;

for(i = 0; i < numbers.length; i++) {
    if (numbers[i] <= 70){
        console.log(numbers[i]);
    }
}

Ad
source: stackoverflow.com
Ad