Introduction and Lesson Overview

Are you prepared to dive into the deep end of TypeScript? Our expedition today will revolve around comprehending two essential instructions: the break and continue commands. The break command, in its simplest terms, stops a looping structure dead in its tracks, disregarding its original condition. On the other hand, the continue command bypasses the remaining loop iteration and immediately proceeds to the following one.

We'll get our hands dirty by understanding these commands using simple for and while loops, before exploring the intricacies of nested loops.

Directing Single 'for' Loop Control — The Break Statement

Recall the for loop? Well, its iterations continue as long as the set condition is met. In this section, our agenda is to introduce and understand the concept of break. Once this command is encountered, the loop abruptly stops, without any hesitation!

Let's imagine a game of hide-and-seek, where every hiding spot corresponds to an iteration of the loop. The game ends when the hidden object (break) is found. Here's how it translates to TypeScript:

Notice how the set of numbers from 0 to 10 couldn't execute fully due to the break at i = 5, terminating the subsequent iterations prematurely.

Directing Single 'for' Loop Control — The Continue Statement

Now, the continue command skips the current iteration and swiftly moves onto the next one. Picture this as picking candies from a jar while deciding to skip a specific candy. That's the essence of the continue command.

Observe how the continue statement effectively omits i = 5, and the loop covers all values from 0 to 9.

Managing Single 'while' Loop Control — Break and Continue

The commands break and continue function in while loops similarly to their behavior in for loops. Imagine scrolling through a playlist, but deciding to skip song number 5:

Now, let's imagine we're flipping through a photo album and wish to stop at a particular picture:

Domination of Nested Loops — Break and Continue

Remember playing with nested puzzle boxes? The break command allows us to conclude the nested loop operation once the puzzle is solved:

It's important to note that the break command exclusively ends the inner loop, and the outer loop continues its execution. Since the puzzle is solved we'd technically want to end both loops but that's a topic for another lesson.

Lesson Summary and Practice

Congratulations! Today's deep dive has equipped us with an understanding of the break and continue commands in TypeScript. This knowledge was then used to control single and nested for and while loops. Make sure to practice what you have learned to cement your new knowledge. Keep coding, and see you in the next lesson!

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