Loops

I. What is a loop?

A loop repeats a set of instructions until a specified condition, called a stopping condition, is reached.

II. For loop

A for loop contains three expressions separated by a semi-colon inside the parentheses:

  • an initialization starts the loop.
  • a stopping condition. If the condition evaluates to true, the code block will run, and if it evaluates to false the code will stop.
  • an iteration statement updates the iterator variable on each loop.

For example

for (let i = 0; i < 3; i++) {
  console.log(i);
}
// Output:
0;
1;
2;

In the code block above:

  • The initialization is let i = 0, so the loop will start counting at 0.
  • The stopping condition is i < 3, so the loop will run as long as i is less than 4.
  • The iteration statement is i++. After each loop, the count value will increase by 1. For the first iteration, the counter will equal 0. For the second iteration, the counter will equal 1, and so on.
  • The code block console.log(i) will execute until the condition evaluates to false.

Loop through an array To loop through each element in an array, we use the array.length property in its condition.

For example

const vacationSpots = ["London", "Copenhagen", "Saigon"];

for (let i = 0; i < vacationSpots.length; i++) {
  console.log(`I would love to visit ${vacationSpots[i]}`);
}

III. While loop

The while loop loops through a block of code as long as a specified condition is true.

while (condition) {
  // code block
}

For example

while (i < 5) {
  text += "The number is " + i;
  i++;
}

IV. Do…While Statements

do...while loops run code at least once and only check the stopping condition after the first execution.

do {
  // code block to be executed
} while (condition);

V. Switch statements

switch (expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
  // code block
}

VI. Looping keywords

1. continue

The continue keyword skips the current iteration.

let result = [];

for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) {
    continue;
  }
  result.push(i);
}

console.log(result);
// Result: [ 1, 3, 5, 7, 9 ]

2. break

The break keyword allows programs to leave a loop during the execution of their block.

let result = [];

for (let i = 0; i < 10; i++) {
  if (i % 3 === 0) {
    break;
  }
  result.push(i);
}

console.log(result);
// Result: [ 1, 2 ]