Salem
Salem

Reputation: 17

Using the continue statement in a for loop

Why does the continue statement print even numbers, but will print odd numbers if replaced by console.log() in the following?

// print even numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) != 0) {
    continue;
  }
  console.log(i);
}

//print odd numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) != 0) {
    console.log(i);
  }
}

Upvotes: 0

Views: 1291

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

When the continue statement is executed, the rest of the contents of the loop body are skipped and execution returns to the top of the loop, to start the next iteration of the loop. So this:

if ((i % 2) != 0) {
  continue;
}

means "If i is odd, skip back to the top of the loop, don't execute the rest of the loop body." That means the odd number isn't printed.

In your second example, you're only outputting when the condition is true, so you've ended up doing the opposite output, but in a different way: Only calling console.log when the number is odd.

You can make the first one output only even numbers by removing the continue, changing the condition, and moving console.log into the if body:

// print even numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) === 0) { // *** Changed condition
    console.log(i);    // *** Moved `console.log`
  }
}

That does even numbers in the same basic way the second one did odd numbers.

Or you can change the second one work like the first one, but in general it's best to avoid using continue (there are probably exceptions to that general rule):

// print odd numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) == 0) { // *** Changed condition
    continue;
  }
  console.log(i);
}

Upvotes: 0

Sim Son
Sim Son

Reputation: 308

In the first example, the loop continues with the next iteration if the number is odd (and therefore the program does not reach console.log()). In this next iteration the number is even and will be printed.

The second example is quite trivial: you only print the number if it is odd.

Upvotes: 1

Related Questions