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.
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:
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.
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:
As you can see, the loop traversed all numbers from 0 to 9, but skipped logging for i = 5, due to the continue statement.
