views:

104

answers:

2

Maybe this is a dumb question but is there a way to return to the top of a loop?

Example:

for(var i = 0; i < 5; i++) {

    if(i == 3)
        return;

    alert(i);
}

What you'd expect in other languages is that the alert would trigger 4 times like so:

alert(0); alert(1); alert(2); alert(4);

but instead, the function is exited immediately when i is 3. What gives?

+11  A: 

Use continue instead of return.

Example: http://jsfiddle.net/TYLgJ/

for(var i = 0; i < 5; i++) {

    if(i == 3)
        continue;

    alert(i);
}

If you wanted to completely halt the loop at that point, you would use break instead of return. The return statement is used to return a value from a function that is being executed.

EDIT: Documentation links provided by @epascarello the comments below.

patrick dw
aha! Thank you very much patrick.
Darcy
continue: https://developer.mozilla.org/en/JavaScript/Reference/Statements/continuereturn: https://developer.mozilla.org/en/JavaScript/Reference/Statements/return
epascarello
@epascarello - Thanks for adding the references. :o)
patrick dw
I guess mine was down-voted too. Down-voters should give a reason.
patrick dw
+2  A: 

For what it's worth, you can also label them:

OUTER_LOOP: for (var o = 0; o < 3; o++) {
  INNER_LOOP: for (var i = 0; i < 3; i++) {
    if (o && i) {
      continue OUTER_LOOP;
    }
    console.info(o, ':', i);
  }
}

outputs:

0 : 0
0 : 1
0 : 2
1 : 0
2 : 0
Sir Robert
+1 Definitely worth noting. :o)
patrick dw