The Continue Statement

Now let's look at the continue statement, which allows us to skip the rest of the current iteration of a loop and continue with the next iteration. Imagine you go running every day, but some days the weather is bad, and you don't want to run. The continue statement allows you to skip such days and continue running on the other days.

For example, we want to print all the numbers between 1 and 10 except those that are multiples of 3:

let number = 1;
while (number <= 10) {
    if (number % 3 === 0) { // If the number is a multiple of 3
        number++;
        continue; // Skip this iteration
    }
    console.log(number);
    number++;
}
// Prints: 1 2 4 5 7 8 10

In this example, we go through the numbers from 1 to 10. If number is a multiple of 3, we increment it by 1 and skip its printing using the continue statement and move to the next iteration of the loop. When number is not a multiple of 3, we print it and increment it by 1. It's important to note that once the program encounters the continue statement, it skips the rest of the commands in the loop's code block and continues with the next iteration. Let's go through a few iterations to make everything clear:

  1. The loop starts, and the value of number is 1.
  2. The condition is skipped since number is not a multiple of 3.
  3. The number (value 1) is printed.
  4. The number is incremented by 1.
  5. We return to the beginning of the loop. Now the number is 2.
  6. The condition is skipped since number is not a multiple of 3.
  7. The number (value 2) is printed.
  8. The number is incremented by 1.
  9. We return to the beginning of the loop. Now the number is 3.
  10. The condition is met, so the number is incremented by 1.
  11. The rest of the iteration is skipped.
  12. We return to the beginning of the loop. Now the number is 4.

Instructions

Using a while loop, iterate count from 1 to 10 and print count when it is not a multiple of 2. Use the continue statement to skip numbers that are multiples of 2. Remember to increment the count variable by 1.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/9

The Continue Statement | Start Coder