Loops
Loops allow us to repeat actions multiple times, either for a fixed number or until a condition is met
The
whileloop repeats instructions until a condition is evaluated astrue
let n = 0;
while (n < 3) {
console.log(n); // Prints 0, then 1, and then 2
n++;
}The
do-whileloop is likewhile, 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 1The
forloop 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-inloop iterates over every key-value pair of an object
The
for-ofloop is likefor-inbut 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
breakkeyword allows us to end a loop suddenly, for example, when a condition is met. After reaching thebreakthe loop is stopped, and the next instructions are skipped, continuing with the main flow of the program
Last updated