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 astrue
let n = 0;
while (n < 3) {
console.log(n); // Prints 0, then 1, and then 2
n++;
}
The
do-while
loop 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 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
let user = {name: "Ana", age: 30};
for (let key in user) {
console.log(key); // Iterate attributes, prints "name" "age"
console.log(user[key]); // Iterate values, prints "Ana" 30
}
The
for-of
loop is likefor-in
but works over iterables
let numbers = [10, 20, 30];
for (let number of numbers) {
console.log(number); // prints 10, 20, 30
}
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.
let numbers = [1, 2, 3];
let letters = ["a", "b"];
for (let letter of letters) { // This loops each time the inner loop finishes
for (let i = 0; i < numbers.length; i++) { // This is done repeartly
console.log(letter + numbers[i]); // This is executed a total of 6 times
}
} // The final output is a1 a2 a3 b1 b2 b3
// Combining for and while
count = 0
while(count < 3){
for (let i = 0; i < 4; i++) {
console.log('Combined Double Cycle'); // Runs 12 times
}
count++;
}
The
break
keyword allows us to end a loop suddenly, for example, when a condition is met. After reaching thebreak
the loop is stopped, and the next instructions are skipped, continuing with the main flow of the program
count = o
while(true){ // This is an infinite loop
if(count < 3){
console.log("Finished")
break // It ends the loop.
}
count++;
}
Last updated