Introduction and Lesson Overview

Are you ready for another exciting journey? Today's mission involves understanding the break and continue commands. The break command immediately ends a loop regardless of the defined condition, while the continue command bypasses the remaining loop iteration and jumps straight to the next one.

We'll start by mastering these controls using simple for and while loops before delving into the complexity of nested loops.

Commanding Single 'for' Loop Control — The Break Statement

Remember the for loop? Its iteration continues until a condition is met. Let's meet a new friend — break. Once encountered, the loop stops, no matter what!

To understand better, let's think of a treasure hunt, where each box is a loop iteration. Opening a box executes the loop, and finding treasure (break) halts the opening spree. Here's how it works in JavaScript:

for (let i = 0; i <= 10; i++) {
  if (i === 5) {
    console.log("Treasure found at position", i); // Our treasure is at the position 5.
    break; // STOP! We got the treasure. No need to continue opening more boxes.
  }
  console.log("No treasure at position:", i);
}
/*
Prints:
No treasure at position: 0
No treasure at position: 1
No treasure at position: 2
No treasure at position: 3
No treasure at position: 4
Treasure found at position 5
*/

See? Even though the loop was intended to go through numbers 0 to 9, due to break at i = 5, the remaining iterations were not executed at all.

Commanding Single 'for' Loop Control — The Continue Statement

The continue command skips the current loop iteration and jumps to the next one. Imagine eating fruits from a basket and deciding to skip an apple. That's exactly what the continue command does. Here's how:

for (let i = 0; i < 10; i++) {
  if (i === 5) { // Position 5 is where the apple is.
    continue; // SKIP! No apple for me, thank you. Onto the next fruit!
  }
  console.log("Eating fruit at position:", i);
}
/*
Prints:
Eating fruit at position: 0
Eating fruit at position: 1
Eating fruit at position: 2
Eating fruit at position: 3
Eating fruit at position: 4
Eating fruit at position: 6
Eating fruit at position: 7
Eating fruit at position: 8
Eating fruit at position: 9
*/

As you can see, the loop traversed all numbers from 0 to 9, but skipped logging for i = 5, due to the continue statement.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal