Mastering Break and Continue Statements in Dart Loops

Introduction and Lesson Overview

Are you prepared to dive into the deep end of Dart? Today, we embark on an exciting journey focused on mastering two fundamental instructions: the break and continue statements. In its most basic terms, the break statement ceases a loop from executing, even if its original condition still holds true. However, the continue statement merely skips the remaining portion of the current iteration, instantly moving on to the next one.

We'll familiarize ourselves with these statements within the context of simple for and while loops before diving into the dynamics of nested loops.

Directing Single "for" Loop Control — The Break Statement

Do you remember what the for loop does? Its iterations persist as long as the condition is met. In this section, we delve into understanding the break statement. Upon encountering this statement, the loop immediately terminates — no questions asked!

Consider this scenario: a game of hide-and-seek, where each hiding spot represents an iteration of the loop. The game ends when the hiding object (break) is found. Here's how it could be presented using Dart:

for (var i = 0; i <= 5; i++) {
  if (i == 3) {
    print('Hidden object found at position $i'); // Our hidden object is at position 3
    break; // STOP! We found the object. No need to search further.
  }
  print('No hidden object at position: $i');
}

// Output:
// No hidden object at position: 0
// No hidden object at position: 1
// No hidden object at position: 2
// Hidden object found at position 3

Notice that the number series from 0 to 5 couldn't fully execute due to the break at i = 3, which prematurely halted the remaining iterations.

Directing Single "for" Loop Control — The Continue Statement

Next, we have the continue statement. This statement, in contrast, opts to skip the current iteration and directly progress to the next. It's akin to choosing candies from a jar but skipping one specific candy.

for (var i = 0; i <= 5; i++) {
  if (i == 3) { // Position 3 has the candy we're avoiding
    continue; // SKIP! Don't take this candy. On to the next one!
  }
  print('Picked candy at position: $i');
}

// Output:
// Picked candy at position: 0
// Picked candy at position: 1
// Picked candy at position: 2
// Picked candy at position: 4
// Picked candy at position: 5

Here, the continue statement effectively excludes i = 3, and the loop covers all values from 0 to 5.

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