Master the different loops in Javascript

Master the different loops in Javascript

Loops make repeating actions simple and quick. A loop can be thought of as a computer version of “copying N rows” or “doing something X times”. For example, in JavaScript, we could translate "Take 5 steps east" with this loop:

for (let step = 0; step < 5; step++) {
   // This will be executed 5 times
   // At each execution, the "step" variable will increase by 1
   // When it reaches 5, the loop will end.
   console.log('Do ' + step + 'step east');
}

There are different types of loops but they are all similar in that they repeat an action a certain number of times (this number can optionally be zero). The different types of loops allow you to use different ways to start and end a loop. Each type of loop can be used depending on the situation and the problem you are trying to solve.

Here are the different loops provided by JavaScript:

The for statement The do...while statement The while statement The label statement The break statement The instruction continues The for...in statement The for...of statement

The for statement

A for loop repeats statements until a given condition no longer holds. The JavaScript for loop is very similar to the one used in C or Java. A for loop is used as follows:

for ([initialExpression]; [condition]; [incrementExpression])
   instruction

Here is what happens when a for loop executes:

The initial expression initialExpression is executed if present. Generally, we use this expression to initialize one or more counters that we will use in the loop. It is possible to use more complex expressions if necessary. It can be used to declare variables. The condition expression is evaluated, if it is true, the instructions contained in the loop are executed. If the condition value is false, the for loop terminates. If the condition is absent, it is considered true. The statement statement is executed. If we want to execute several instructions, we will use a block of instructions ({ ... }) in order to group them. If present, the update expression incrementExpression is executed. We then return to step 2.

const test = 5;

for (let i = 0; i < test; i++) {
    console.log(i); // 0, 1, 2, 3, 4
}

'do...while statement

The do...while statement allows a set of statements to be repeated until a given condition is no longer verified. (literally "do...while" means "to do... while"). A do...while statement is used as follows:

do
  instruction
while (condition);

statement is executed at least once before the condition is verified. To use multiple statements in this place, we will use a block statement ({ ... }) to group different statements together. If the condition is verified, the instruction is executed again. At the end of each execution, the condition is checked. When the condition is no longer verified (evaluates false or an equivalent value), the execution of the do…while instruction is stopped and control passes to the following instruction.

Example In the following example, the do loop is executed at least once and repeated until i is no longer less than 5.

let i = 0;
do {
  i += 1;
  console.log(i);
} while (i < 5);

The while statement

A while statement executes a statement as long as a given condition is true. This while statement is used as follows:

while (condition)
  instruction

If the condition is not verified, the statement statement is not executed and control passes directly to the statement following the loop.

The test of the condition is performed before executing the instruction. If the condition returns true (or an equivalent value), statement will be executed and the condition will be tested again. If the condition returns false (or an equivalent value), execution stops and control is passed to the statement following while.

To be able to use several instructions in the loop, we will use a block instruction ({ ... }) in order to group them.

Example 1

The following while loop allows iterations as long as n is less than 3:

let n = 0;
let x = 0;
while (n < 3) {
   n++;
   x += n;
}

À chaque itération, la boucle incrémente n et ajoute la valeur de n à x. x et n prendront ainsi les valeurs suivantes :

Après la première itération : n = 1 et x = 1 Après la deuxième itération : n = 2 et x = 3 Après la troisième itération : n = 3 et x = 6 Une fois la troisième itération effectuée, la condition n < 3 n'est plus vérifiée, par conséquent, la boucle se termine.

Exemple 2

Attention à éviter les boucles infinies. Il faut bien s'assurer que la condition utilisée dans la boucle ne soit plus vérifiée à un moment donné. Si la condition est toujours vérifiée, la boucle se répétera sans jamais s'arrêter. Dans l'exemple qui suit, les instructions contenues dans la boucle while s'exécutent sans discontinuer car la condition est toujours vérifiée :

while (true) {
  console.log("Coucou monde !");
}

The label statement

A label allows you to provide an identifier for an instruction in order to refer to it from another place in the program. We can thus identify a loop thanks to a label then use the break or continue instructions to indicate whether the program must interrupt or continue the execution of this loop.

A label is used as follows:

label: instruction The value of label can be any valid JavaScript identifier (and must not be a reserved word for the language). The statement can be any valid JavaScript statement (including a block).

Example

In this example, we use a memoBoucle label to identify a while loop.

memoLoop:
while (memo == true) {
  doQQC();
}

Note: For more details on this statement, see the JavaScript reference page for label.

The break statement

The break statement is used to end the execution of a loop, a switch statement, or with a label.

When break is used without a label, it causes the end of the while, do-while, for, or switch statement in which it is written (the most nested statement is finished), control is then passed to the statement next. When break is used with a label, it causes the corresponding statement to terminate. The syntax of this instruction therefore has two forms:

break; break label;

The first form allows you to interrupt the most nested loop (or the switch) in which you are. The second form interrupts the execution of an instruction identified by a label.

Example 1 In the following example, we iterate over an array using a loop until we find an element whose value is testValue:

for (i = 0; i < a.length; i++) {
  if (a[i] === testValue) {
    break;
  }
}

Example 2

Here, we use break in two ways: with an instruction represented by a label and without.

let x = 0;
let z = 0;
labelCancelLoop: while (true) {
  console.log("Outer loop: " + x);
  x += 1;
  z=1;
  while (true) {
    console.log("Inner loop: " + z);
    z+= 1;
    if (z === 10 && x === 10) {
      break labelCancelLoop;
    } else if (z === 10) {
      break;
    }
  }
}

The instruction continues

The continue statement allows you to resume a while, do-while, for, or label statement.

When continue is used without a label, the current iteration of the loop (the most nested one) is terminated and the loop proceeds to execute the next iteration. Unlike the break statement, continue does not entirely stop loop execution. If used in a while loop, the iteration resumes at the stopping condition. In a for loop, iteration resumes at the increment expression for the loop. When continue is used with a label, it is applied to the corresponding loop statement. The continue statement is therefore used as follows:

keep on going;
continue label;

Example 1

In the following example, we use a while loop with a continue instruction which is executed when i is 3. Here, n will therefore take the values ​​1, 3, 7, and 12.

let i = 0;
let n = 0;
while (i < 5) {
  i++;
  if (i === 3) {
    keep on going;
  }
  n += i;
  console.log(n);
}
// 1, 3, 7, 12

Example 2

In the following example, we have a statement labeled verifJ which contains another statement labeled verifJ. If the continue statement is used, the program resumes execution at the beginning of the checkJ statement. Each time continue is used, checkJ iterates until its condition returns false. When this is the case, the rest of the statement verifJ is executed.

If continue used the label checkJ, the program would continue at the beginning of the statement checkJ

let i = 0;
let j = 8;

*checkJ*: while (i < 4) {
  console. log("i: " + i);
  i += 1;

  *checkJ*: while (j > 4) {
    console. log("j: "+ j);
    j-=1;
    if ((j % 2) === 0){
      continue check;
    }
    console.log(j + " is odd.");
   }
   console. log("i = " + i);
   console. log("j = " + j);
}

The for...in statement

The for...in statement allows you to iterate over all the enumerable properties of an object. For each property, JavaScript will execute the indicated statement. This instruction is used as follows:

for (variable in object) {
  instruction
}

Example

The following function takes as argument an object and the name of this object. It then loops through the properties of the object and returns a string that lists the properties with their respective names and values:

function *displayProps*(obj, objName) {
  var result = "";
  for (var i in obj) {
    result += objName + "." + i + " = " + obj[i] + "\n";
  }
  result += "\n";
  return result;
}

For a car object whose properties are manufacturer and model, result would be:

car.manufacturer = Ford
car.model = Mustang

Arrays and for...in

Although it is tempting to use this statement to iterate through the elements of an Array object, it can have unexpected behaviors. This is because for...in allows iterating through user-defined properties as well as array elements. Thus, if we modify an Array object by adding properties and/or methods to it, the for...in loop will return the name of these new properties in addition to the indices of the elements of the array. This is why it is better to use a for loop with the indices of the array to traverse its elements.

The for...of statement

The for...of statement creates a loop that works with iterable objects (which include Array, Map, Set, the arguments object, etc.). The loop calls an iteration mechanism specific to the object used and it traverses the object and the values ​​of its various properties.

for (variable of object) {
  instruction
}

The following example illustrates the difference between a for...of loop and a for...in loop. for...in iterates over an object's property names while for...of iterates over property values:

let arr = [3, 5, 7];
arr.toto = "hello";

for (let i in arr) {
   console.log(i); // displays 0, 1, 2, "toto" in the console
}

for (let i of arr) {
   console.log(i); // displays 3, 5, 7 in the console
}