• 15 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 19/01/2024

Use the right loop to repeat tasks

In programming, there are sets of instructions you will need to repeat multiple times. Sometimes, you will know the number of repetitions in advance, other times you will not. There will also be times when the number of times does not matter, and you wish to repeat the code until a certain condition is met. For all of these purposes, we will use loops.

How many times? The for loop

Let's say that you have 10 passengers to board, and for now you are not concerned with the order in which they are boarded. Use a  for loop to board them one by one until you reach 10:

const numberOfPassengers = 10;

for (let i = 0; i < numberOfPassengers; i++) {
    console.log('Passenger boarded!');
}

For this type of  for loop, create an index variable i which serves as a counter for the number of times it has been executed — this is why it starts at zero, as you have not been through the loop yet.

The second command in the  for parentheses is the condition for continuing the loop: as soon as it evaluates to  false, you end the loop. In this case, you want it to execute as many times as there are passengers, so once index  i hits 10 (looped 10 times), you want to stop, as there are no passengers left.

The third command tells the for loop to increment  i  (add 1) every time it is run. This is what allows you to keep track of the number of loop executions.

JavaScript will finish the loop before running any other code, so if you were to write this:

const numberOfPassengers = 10;

for (let i = 0; i < numberOfPassengers; i++) {
    console.log('Passenger boarded!');
}

console.log('All passengers boarded!');

The final console log would print after the 10 passengers are boarded.

Working with indices (the plural of index) is all very well, but what if you are working with an array of passengers and need to board them in order?

Dealing with arrays:  forof  and  forin

There are many situations in which you will have an array and will need to work your way through it, doing something with each element. This could be updating prices on a menu, processing data from a database, or boarding passengers in order.

The old-fashioned way of looping through an array was to use the  for loop you saw above, along with its  length  property. For example, with an array called  passengers:

for (let i = 0; i < passengers.length; i++) {
    console.log('Passenger boarded!');
}

While this works, there are two easier ways of looping through (or iterating over) arrays.

The forin loop

The forin loop works in a similar way to the above normal for loop example, but is easier to read, and does all the iteration work for you:

const passengers = [
    'Will Alexander',
    'Sarah Kate',
    'Audrey Simon',
    'Tau Perkington'
]

for (let i in passengers) {
    console.log('Boarding passenger ' + passengers[i]);
}

As in the previous example,  i starts at zero automatically, and increments with each loop. So you log passengers[0], then passengers[1], then passengers[2], etc. until all passengers have been iterated over. You can of course print each element to the console, as each is a string containing the name of the passenger.

The forof loop

For cases where the specific index of an element is not needed during iteration, you can use a  for …of loop: 

If you take the previous example and use a  for…of loop instead, you get:

const passengers = [
    'Will Alexander',
    'Sarah Kate',
    'Audrey Simon',
    'Tau Perkington'
]

for (let passenger of passengers) {
    console.log('Boarding passenger ' + passenger);
}

This achieves the exact same result, but in a more readable way, as you do not need to think about indices and arrays: you simply receive each element in order. This is even more useful if the array is a little more complex, containing objects for example:

const passengers = [
    {
        name: 'Will Alexander',
        ticketNumber: 209542
    },
    {
        name: 'Sarah Kate',
        ticketNumber: 169336
    },
    {
        name: 'Audrey Simon',
        ticketNumber: 779042
    },
    {
        name: 'Tau Perkington',
        ticketNumber: 703911
    }
]

for (let passenger of passengers) {
    console.log('Boarding passenger ' + passenger.name + ' with ticket number ' + passenger.ticketNumber);
}

All in all, it's much easier to read and reason about than using indices if you don't need them!

Practice using  for  loops!

Head to CodePen Exercise P2CH3a and follow the instructions below to practice using arrays and for loops.

Your episode component has been restructured, and the episodes are now being imported from a database. You must now implement code which will automatically reset viewing information for all episodes. This will be accomplished by iterating over the episodes array, setting each episode's hasBeenWatched property to false.

The episodes array has been declared for you.

  1. Using either a for, a for…in, or a for…of loop, iterate over the episodes array and set each episode's hasBeenWatched property to false. Check that all episodes now say "Not yet watched."

  2. Try setting all episodes as having been watched. Did that work too?

Solution:

Once you've given it a go, watch me code a solution and see how your approach compares. And here is a new CodePen with a solution to the exercice.

This kind of loop is great for a set number of iterations. However, you may not always know how many times a loop needs to be executed.

Keep going until I say we're done: the while loop

while loop checks if a condition is true. If it is, the loop continues; if it is not, it stops. Back to the plane boarding example: let's say you have variables representing the number of remaining seats and the number of remaining passengers. You want to board until you either run out of seats or passengers:

let seatsLeft = 10;
let passengersStillToBoard = 8;

let passengersBoarded = 0;

while (seatsLeft > 0 && passengersStillToBoard > 0) {
    passengersBoarded++; // one passenger boards
    passengersStillToBoard--; // so there is one fewer still to board
    seatsLeft--; // and one fewer seat
}

console.log(passengersBoarded); // prints 8, as there are 8 passengers for 10 seats

This  while loop will continue to execute until either seatsLeft or passengersStillToBoard hits zero, at which point it will terminate.

Let's recap!

In this chapter, you looked at two ways of repeating tasks:

  • The for loop, for a set number of iterations.

  • The while loop, for when the required number of iterations is unknown.

In the next chapter, we'll have a look at what to do when things don't quite go according to plan.

Exemple de certificat de réussite
Exemple de certificat de réussite