Mastering Loop Control: Break and Continue in TypeScript

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:

for (let i = 0; i <= 10; i++) {
  if (i === 5) {
    console.log(`Hidden object found at position ${i}`); // Our hidden object is at position 5
    break; // STOP! We found the object. No need to search further.
  }
  console.log(`No hidden object at position:${i}`);
}

/*
Prints:
No hidden object at position: 0
No hidden object at position: 1
No hidden object at position: 2
No hidden object at position: 3
No hidden object at position: 4
Hidden object found at position 5
*/

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.

for (let i = 0; i < 10; i++) {
  if (i === 5) { // Position 5 has the candy we're avoiding
    continue; // SKIP! No candy for me, thank you. On to the next candy!
  }
  console.log(`Picked candy at position: ${i}`);
}
/*
Prints:
Picked candy at position: 0
Picked candy at position: 1
Picked candy at position: 2
Picked candy at position: 3
Picked candy at position: 4
Picked candy at position: 6
Picked candy at position: 7
Picked candy at position: 8
Picked candy at position: 9
*/

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

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