pimvdb
pimvdb

Reputation: 154818

Using continue in a do-while loop

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?

Upvotes: 20

Views: 13461

Answers (7)

Joshua Pinter
Joshua Pinter

Reputation: 47471

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.

Upvotes: 1

Guffa
Guffa

Reputation: 700242

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.

Upvotes: 4

Kevin McKelvin
Kevin McKelvin

Reputation: 3547

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.

Upvotes: 15

oezi
oezi

Reputation: 51797

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.

Upvotes: 5

Graham Wager
Graham Wager

Reputation: 1887

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

Upvotes: 13

Munter
Munter

Reputation: 1089

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

Upvotes: 5

Griffin
Griffin

Reputation: 14614

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

Upvotes: 3

Related Questions