4

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?

3
  • 4
    Could you give an example of 'other languages'? Commented Oct 13, 2010 at 19:13
  • 1
    What languages are you thinking of where returning in the middle of a loop makes the loop continue? It's not so in any language I know. Commented Oct 13, 2010 at 19:14
  • 2
    C# does not continue the loop - once you execute the 'return' statement, the function exits immediately, just as it does in javascript. C# also uses the 'continue' statement for the execution flow you are trying to accomplish. Commented Oct 13, 2010 at 21:06

2 Answers 2

20

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.

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

3 Comments

@epascarello - Thanks for adding the references. :o)
I guess mine was down-voted too. Down-voters should give a reason.
7

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.