Coding for Kids

Loops: Break and Continue

Loops are used all the time in programming. You have options between while and for loops based on your needs.

A loop typically ends when a task is completed or a condition changes (unless you set yourself up with an infinite loop).

But there are times where you need to control the loop from inside the loop itself.

Controlling a loop from the inside

There are two special keywords whose job is to control the flow of a loop from within the loop itself.

In both cases, you simply put the keyword on its own line in the code.

Continue

Use the continue keyword to return immediately to the top of the loop for the next iteration without completing the rest of the code in the loop. This keeps the loop going overall, but you can skip certain sections if you need to.

Let's say your teacher is calling up each student to the front of the class to introduce themselves, read a poem, then take a bow. The teacher calls one student after another. But if one student is absent, the teacher just moves on to the next person instead of looking for the introduction and so on. This is essentially what a continue is doing.

Example:

Let's take an example of counting by 10 up to 100. But we want to skip the number 60. Eh, why not?

  • for (let i = 0; i <= 100; i += 10)
  • {
    • if (i === 60)
    • {
      • continue;
    • }
    • console.log(i);
  • }
See this in repl.it

The continue makes the loop jump up to the top and so it skips the console.log() call.

Break

Use break to exit out of a loop completely without finishing anything else in it. It doesn't run any more of the code in the block and it doesn't do any more iterations. The loop just stops and the program moves on to whatever else is next.

Let's use our classroom idea from above. Assume all the students are in class, so everyone is going to be called up to make their introduction, read their poem, and then take their bow. There's no escape this time! But then... uh oh, the fire alarm goes off! The teacher escorts your class to safety and you wait there. The fire alarm interrupted the loop, so you're finished with readings for the day.

Example:

We are going to count again. We're going to count by 10 and go up to 100. But this time, once we get to 60, someone in the room shouts and interrupts the count, so we stop.

  • for (let i = 0; i <= 100; i += 10)
  • {
    • if (i === 60)
    • {
      • break;
    • }
    • console.log(i);
  • }
See this in repl.it

The break puts a stop to everything. The loop counts up like it did before, starting a 0 and going up by 10. But this time, the display stops at 50. Once the count is at 60, the loop breaks and exits. It never gets to the console.log() line to show the 60.

Breaking out of a switch

If you've seen switch statements, then you know that the break keyword is important there too. A switch tests for numerous cases and for each one, generally, you want to stop the switch and exit out. You use the break command here too.

You can read more switch statements here.

Using break and continue together

There are times where you have a lot of situations to control for in your loop. You may want to skip over things in some situations and end the process in others. You can put both of these keywords to work for you.

Example:

Sticking with our counting to 100 example, let's still count to 100, but let's count by 3 this time. We'll display the values, but only the odd ones. And if, along the way, we go higher than the number 50, then let's stop and walk away.

  • for (let i = 0; i < 100; i += 3)
  • {
    • //checks for an even number
    • if (i % 2 === 0)
    • {
      • //go to the top of the loop
      • continue;
    • }
    •  
    • if (i > 50)
    • {
      • //exit the loop
      • break;
    • }
    •  
    • console.log(i);
  • }     //go back to the top of the loop
  •  
  • //this is outside the loop
  • console.log("Ok, I'm done.");
See this in repl.it

Try it out. Does it do what you think it will do?

Let's break it down.

  1. The loop will start at 0.
  2. The loop continues to 100 non-inclusive.
    • Non-inclusive means not including 100.
  3. The index, i, will increase by 3 each time through the loop.
    • i += 3
  4. If the iterator, i, is an even number then continue the loop.
    • i % 2 === 0 tests for even numbers using modulo.
    • continue means to go back to the top and skip the rest of the code underneath.
    • This also means it won't print the number to the console.
  5. If the index, i, is greater than 50, then break out of the loop.
    • This means it skips the printing of the number.
    • This also means it no longer keeps looping.
  6. Once out of the loop, we report that we are done.

What do we get?

Coding for Kids Sidenote: This is meant as a demonstrative example. If you really wanted to end the loop above 50, you wouldn't even bother making the loop go up to 100. However, you could use a variable in place of 50 and that may cause some different results if you set different values to the variable.

Notice, they count up by 3, but there are no even numbers shown (like 6, 18, etc.) and there's nothing above 50.

Fire drills, absentees, and poetry

For practice, let's combine the two classroom situations from above and make it into a loop using all that we know.

For added practice, we're going to make an array of students and loop through that. This is more likely how you'll use these statements.

For even more added practice, we're going to use a random number to determine if there's a fire drill or if someone is absent. You may need to run it a couple of times to see its effect.

  • //let's make the student roster and the teacher
  • let teacher = "Dr. Wolf";
  • let students = ["Steve", "Kevin", "Kim", "Lisa", "John", "Max", "Shadow", "Merlin", "Monty"];
  •  
  • for (let number = 0; number < students.length; number++)
  • {
    • //this is to split up the display so we can see it better
    • console.log("----");
    •  
    • //helper variable for readability
    • let student = students[number];
    •  
    • //pick an integer from 0 to 99
    • let randomNumber = Math.floor(Math.random() * 100);
    •  
    • //Let's give a 15% chance of having a fire drill
    • if (randomNumber < 15)
    • {
      • console.log("Fire! Fire! Leave immediately!");
      • break;
    • }
    •  
    • console.log(teacher + " calls " + student + " to the front of the room.");
    •  
    • //hey, maybe the student is absent!
    • if (randomNumber > 80)
    • {
      • console.log("But it looks like " + student + " is absent today.");
      • continue;
    • }
    •  
    • //time to read the poem
    • console.log("My name is " + student + " and here is my poem:");
    • console.log(randomNumber + " bunnies fell from the sky, but I don't know why.");
    • console.log("[" + student + " bows and sits back down.]");
  • }
  • console.log(teacher + " dismisses the class.");
See this in repl.it

That's a hefty bit of code, but see if you can follow it through. Run it a few times. Do you get a fire drill? Is anyone ever absent? Play with the values and the names. Have some fun.

Continue to break out of your shell!

—Dr. Wolf