DEV Community

Cover image for Let's Talk About Break and Continue
oyinade olawoyin
oyinade olawoyin

Posted on

Let's Talk About Break and Continue

In the third article of this series, we talked about the for and while loops. Both are like telling someone to run an errand for you.

A for loop helps you go through a collection of items, like a bag or a list. It gets each item out for you, one after another, and once it reaches the end of the list, it stops checking and ends the loop.

A while loop is like telling the worker to keep looking around the market until he finds the orange stall. He keeps looking while the answer is still "not yet," and he stops once he finds it. A while loop is useful when you don't know how many times the loop will need to run before a condition is met. A for loop, on the other hand, is commonly used when you want to go through a collection of items or repeat an action a specific number of times.

So, what do break and continue have to do with for and while loops?

Imagine you want the worker from our earlier example to go through a bag of items using a for loop. You're specifically looking for a ball, and once you find it, you're no longer interested in the rest of the items in the bag. You don't want the worker to waste time checking the remaining items either, so you use the break statement to tell him to stop searching and let you know he found the ball.

Here's an example:

let bag = ["book", "shoe", "ball", "pen"];

for (let i = 0; i < bag.length; i++) {
    if (bag[i] === "ball") {
        console.log("Found the ball!");
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, once the loop finds the ball, break stops it from checking the remaining items in the bag.

And it's the same with a while loop. You can tell the computer that once it gets the result you're looking for, it doesn't need to keep going. It can just stop searching and give you the result.

Let's go back to our earlier example of looking for an orange stall at the market. In the last post, we used a variable called orange_stall to tell the loop when to stop:

let orange_stall = false;
let stallsChecked = 0;

while (!orange_stall) {
    stallsChecked++;

    if (stallsChecked === 3) {
        orange_stall = true;
        console.log("Stall " + stallsChecked + " sells oranges!");
    } else {
        console.log("Stall " + stallsChecked + " isn't it. Still looking...");
    }
}

console.log("I've found the orange stall! Now I can buy the oranges.");
Enter fullscreen mode Exit fullscreen mode

This works, but we needed an extra variable just to keep track of whether the stall had been found. Here's another way to write the same search. With break, we can skip that variable. We tell the loop to keep running, and the moment the worker finds the stall, break stops it:

let stallsChecked = 0;

while (true) {
    stallsChecked++;

    if (stallsChecked === 3) {
        console.log("Stall " + stallsChecked + " sells oranges!");
        break;
    }

    console.log("Stall " + stallsChecked + " isn't it. Still looking...");
}

console.log("I've found the orange stall! Now I can buy the oranges.");
Enter fullscreen mode Exit fullscreen mode

Both versions print the same thing:

Stall 1 isn't it. Still looking...
Stall 2 isn't it. Still looking...
Stall 3 sells oranges!
I've found the orange stall! Now I can buy the oranges.
Enter fullscreen mode Exit fullscreen mode

Here, the worker checks the stalls one after another. When he reaches the third stall, he finds the oranges, and the break statement stops the loop right there instead of checking more stalls.

while (true) would normally run forever, so break is what gives it a way out. This is different from the infinite loop we warned about earlier, because here we've planned the exit.

We're using the third stall as an example of where the worker finds the oranges. In a real program, the condition would check whether the stall actually sells oranges.

What about continue?

The continue statement is used in a loop to tell the computer to skip the current iteration and move on to the next one.

Let's use another example. Imagine you're sending your worker to your debtors' houses to collect the money they owe you. But you give the worker a condition: if a debtor on the list has already paid in full, the worker shouldn't bother visiting their house. He should skip that name and move on to the next one on the list.

Here's how it works with a for loop:

let debtors = [
    { name: "Tunde", paidInFull: true },
    { name: "Ada", paidInFull: false },
    { name: "John", paidInFull: false }
];

for (let i = 0; i < debtors.length; i++) {
    if (debtors[i].paidInFull) {
        continue;
    }

    console.log("Visit " + debtors[i].name + " to collect the money.");
}
Enter fullscreen mode Exit fullscreen mode

In this example, the worker skips Tunde because he has already paid in full. The worker then moves on to Ada and John because they haven't paid yet.

In a for loop, i++ still runs after continue, so the loop moves on to the next item without any extra handling.

You can also use continue with a while loop. Here's the same example written with a while loop:

let debtors = [
    { name: "Tunde", paidInFull: true },
    { name: "Ada", paidInFull: false },
    { name: "John", paidInFull: false }
];

let i = 0;

while (i < debtors.length) {
    let debtor = debtors[i];
    i++;

    if (debtor.paidInFull) {
        continue;
    }

    console.log("Visit " + debtor.name + " to collect the money.");
}
Enter fullscreen mode Exit fullscreen mode

This works the same way as the for loop example. The worker checks each debtor on the list. When he gets to Tunde, he sees that Tunde has already paid in full, so continue tells him to skip the console.log() line and move on to the next name. The worker then checks Ada and John and visits each of them.

Notice that we increase i before the continue statement. This is important because, unlike a for loop, a while loop doesn't update the counter for us. We need to make sure the counter changes before skipping to the next iteration. Otherwise, the worker might keep checking the same debtor over and over again.

And that's how continue works. It skips a particular iteration, allowing the computer to move on to the next one without performing the remaining actions in the current iteration.

So, if break stops the computer from checking the remaining items in a list or ends a search in a while loop, continue skips the current iteration and moves on to the next one.

Both are useful when you want to control how your loops work.

Thanks for reading, and I hope you find it helpful.

Top comments (0)