Bustin’ Out

Sometimes, while you are in a loop, you will want to change the normal flow of the loop. For example, you are in a for loop, and after the 5th item, you wish to exit the loop, perhaps in response to some signal (e.g., a cancellation flag was set).

You can always use return to exit the entire function that you are in. Beyond that, though, there are two loop control statements that you can use: break and continue. These work much like their counterparts in Java and other programming languages.

break

break says “abandon the loop”:

  var i = 0;

  while (i < 10) {
    i++

    if (i == 5) break

    println(i)
  }

This results in:

1
2
3
4

Once i is equal to 5, we break out of the loop. Since we are doing that before the println() call, we do not print 5 to the output.

continue

continue says “skip the rest of this pass through the loop, and move along to the next pass through the loop”:

  var i = 0;

  while (i < 10) {
    i++

    if (i==5) continue

    println(i)
  }

This gives us:

1
2
3
4
6
7
8
9
10

We are going through the loop all 10 times, unlike in the break case. However, we are skipping part of the loop code via continue — specifically, we are skipping over the println() call. As a result, 5 does not appear in the output, though all the other values do.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.