Question

MDN states:

When you use continue without a label, it terminates the current iteration of the innermost enclosing while, do-while or for statement and continues execution of the loop with the next iteration.

I'm not sure why the following piece of code does not work as I expect.

do {
  continue;
} while(false);

Even though the while condition is false, I expect it to run forever since continue jumps towards the start of the block, which immediately executes continue again, etc. Somehow however, the loop terminates after one iteration. It looks like continue is ignored.

How does continue in a do-while loop work?

Was it helpful?

Solution

Check out this jsFiddle: http://jsfiddle.net/YdpJ2/3/

var getFalse = function() {
  alert("Called getFalse!");
  return false;
};

do {
  continue;
  alert("Past the continue? That's impossible.");
} while( getFalse() );​

It appears to hit the continue, then break out of that iteration to run the check condition. Since the condition is false, it terminates.

OTHER TIPS

continue does not skip the check while(false) but simply ignores the rest of the code within the brackets.

Continue stops execution of the rest of the code in the block and jumps directly to the next iteration of your loop.

Since you are doing while(false) there is no next iteration

continue doesn't start over the current iteration again but skips to the next one (as said in the MDN-quote).

because of a false condition, there is no next iteration - so the whole loop is completed.

After the continue, the loop conditional is evaluated, since it is false, the loop will terminate.

I expect it to run forever since continue jumps towards the start of the block

The continue doesn't jump to the start of the block, it jumps to the end of the block.

Use while(true) to get an infinite loop.

If you replaced while(false) with while(true), you would get an infinite loop.

do {
  continue;
} while(true);

continue skips to the end of the block, which in a do-while loop, will execute the conditional statement.

In your case, your condition was false and therefore it terminates the loop. If that condition is true, it would continue at the start of the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top