Programmers are lazy people. Instead of repeating a task 10 times, they rather spend some time up front, create a procedure that can be repeated, and run that 10 times.

This can be done on several levels. By creating automated tasks for your day to day activities, for example.

When you do this inside your programs, that’s what we call a loop.

Here’s an example of a loop. It’s written using JavaScript:

const list = [1, 2, 3, 4, 5]
for (let value of list) {
  console.log(value)
}

This loop will run 5 times, exactly like the elements found in the list array, and will print the content it finds. The loop will automatically end when the list ends.

Some other kind of loops available in JavaScript do not have a fixed end like this. It’s the case of the while loop, which always checks for a condition before running the loop:

while (true) {
  //do something
}

In this case the condition is always true, so the loop will run forever. If you had

while (false) {
  //do something
}

the loop would never run, and the control goes to the instructions you give next.

Using loops you can usually decide to break when a particular situation happens.

In JavaScript this can be done using the break statement:

const list = [1, 2, 3, 4, 5]
for (let value of list) {
  console.log(value)
  break
}

This will break the loop at the end of the first execution, so instead of printing all the 5 numbers, it will only print one.

Loops can be tricky at times, but they are highly useful.


Go to the next lesson