Using continue in a do-while loop

pimvdb picture pimvdb · Jun 30, 2012 · Viewed 8.5k times · Source

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?

Answer

Kevin McKelvin picture Kevin McKelvin · Jun 30, 2012

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.