Loops

Loops allow us to repeat actions multiple times, either for a fixed number or until a condition is met

  • The while loop repeats instructions until a condition is evaluated as true

let n = 0;
while (n < 3) {
  console.log(n); // Prints 0,  then 1, and then 2
  n++;
}

  • The do-while loop is like while, but it guarantees that the code runs at least once

let i = 0;
do {
  i++;
} while (i > 3); // This is false so the instructions are not repeated
console.log(i); // It still was done 1 time, so it prints 1

  • The for loop is used to repeat instructions a fixed number of times. It consists of an initialization, a stopping condition, and an increment

for (let i = 0; i < 5; i++) { // Start at 0, until 4, incrementing 1 in each cycle
  console.log(i); // Prints 0 1 2 3 4
}

  • The for-in loop iterates over every key-value pair of an object


  • The for-of loop is like for-in but works over iterables


  • Loops can also be nested in any of their combinations, where the inner loop will be the principal running at any moment, and once completed, pass to the next iteration of the outer loop and continue.


  • The break keyword allows us to end a loop suddenly, for example, when a condition is met. After reaching the break the loop is stopped, and the next instructions are skipped, continuing with the main flow of the program

Last updated