0

I am trying use Javascript continue statement inside the while loop but it loops infinitely

Can you explain me?

var john = ['john', 'smith', 1990, 'designer', false, 'blue' ];

var i = 0;
while ( i < john.length) {
    if( typeof john[i] !== 'string') continue;
        console.log( john[i]);
    i++;
}
3
  • 1
    Calling continue skips the rest of the loop, including the i++, so once i is 2 the loops runs forever. Commented Feb 5, 2019 at 5:34
  • but I havê set a condition that only skip if the value is not string and there are condition how many times it's should loop Commented Feb 5, 2019 at 5:36
  • When i reaches 2, typeof john[i] is "number" , so JS calls continue. The loop continues, but i is still 2. Just use this instead: jsfiddle.net/khrismuc/jn8pwzmc Commented Feb 5, 2019 at 5:38

2 Answers 2

1

Every time you use the keyword continue you are skipping the rest of the code below it and jumping back to the top of your while loop. This means that i++ is never reached once you continue, and so, you will always be looking at the integer 1990 in your array. Thus continue will always be called as your if statement will be stuck looking like so:

if(typeof 1990 !=== 'string') { 
  // true so code will fire
  continue; // you reach continue so your loop runs again, running the same if statement check as you haven't increased 'i' (so it checks the same element)
}
// all code below here will not be run (as 'continue' is used above)

Instead, you need to increment in your if statement and outside of it. Allowing you to look at the next value in your array:

var john = ['john', 'smith', 1990, 'designer', false, 'blue' ];

var i = 0;
while ( i < john.length) {
    if( typeof john[i] !== 'string') {
       i++; // go to next index
       continue;
     }
     console.log( john[i]);
     i++;
}

Sign up to request clarification or add additional context in comments.

Comments

1

You have written continue before incrementing the value of i.

You should increment the value of i before continue, like so:

var john = ['john', 'smith', 1990, 'designer', false, 'blue' ];

var i = 0;
while ( i < john.length) {

    if( typeof john[i] !== 'string') {
       i++;
       continue;
    }  
    console.log( john[i]);
    i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.