Coding for Kids

Loops

Computers often need to repeat certain processes over and over again. We do too, if you think about it. When you tie your shoes, first you tie one shoe, then you repeat and tie the other shoe.

A loop is a section of code that repeats over and over until a certain condition is met.

The condition can be a number of things. It could be until a counter reaches a certain number, like counting to ten before trying to find your friends in a game of hide-and-seek. A condition can also be when a Boolean flag changes or when a comparison is no longer true.

The basic structure of a loop

  1. Declare the loop
  2. Initialize a variable for the loop to use
  3. Set the ending condition for the loop
  4. Create a code block of what you want the loop to do while it's running
  5. Make sure to have a way for the loop to end

Types of loops

There are three main types of loops in JavaScript.

The While Loop

A while loop is useful when you don't know how many times you need to complete the loop.

How many licks does it take to get to the center of a Tootsie pop? Well, you don't know, so you keep licking and licking until you get to the center. In this case, the loop runs until you reach the center, then it stops.

There is also a special case of this loop called a do...while loop.

Read more about while loops.

The For Loop

A for is most useful when you do know how many times you need to run the loop.

If you're playing cards and you need to deal out seven cards to each player, you know how many cards to give out. You keep handing them out until you've counted out the right number of cards.

These loops are often used to loop through an array to access each element inside.

Read more about for loops.

The For...In Loop

A for...in loop is used to loop through objects. This allows you to access each of the objects's properties. This has many uses once you're comfortable with using them.

Read more about for...in loops.

How did that song go? Loop, there it is! Loop, there it is!

—Dr. Wolf