How to skip to next in javascript in a for-in with a while inside?

Ram Iyer picture Ram Iyer · Feb 23, 2013 · Viewed 43.4k times · Source

I have a short javascript code where I need to skip to next in the for loop....see below:

var y = new Array ('1', '2', '3', '4');
for (var x in y) {
   callFunctionOne(y[x]);
   while (condition){
       condition = callFunctionTwo(y[x]);
       //now want to move to the next item so 
       // invoke callFunctionTwo() again...
   }
}

Wanted to keep it simple so syntax may be error free.

Answer

Blender picture Blender · Feb 23, 2013

Don't iterate over arrays using for...in. That syntax is for iterating over the properties of an object, which isn't what you're after.

As for your actual question, you can use the continue:

var y = [1, 2, 3, 4];

for (var i = 0; i < y.length; i++) {
    if (y[i] == 2) {
        continue;
    }

    console.log(y[i]);
}

This will print:

1
3
4

Actually, it looks like you want to break out of the while loop. You can use break for that:

while (condition){
    condition = callFunctionTwo(y[x]);
    break;
}

Take a look at do...while loops as well.