JavaScript Loops: For, While, and Do-While
Understanding Loops in JavaScript
Loops are used to execute a block of code repeatedly until a specified condition is met. The most common types of loops in JavaScript are for
, while
, and do-while
.
Example 1: For Loop
// for loop
// for(initialization; condition; increment/decrement) {
// // code to be executed
// }
for(let i = 1; i <= 10; i++) {
console.log(i);
}
This for
loop initializes i
to 1 and increments it by 1 until it reaches 10, logging each value of i
to the console.
Example 2: Iterating Over an Array
let food = ["Burger", "Momos", "Roti", "Sabji", "Salad"];
for(let i = food.length - 1; i >= 0; i--) {
console.log(food[i]);
}
This loop iterates over the food
array in reverse order, logging each food item to the console.
Example 3: Nested Loops
for(let i = 1; i <= 5; i++) {
for(let j = 1; j <= 5; j++) {
console.log(`Outer: ${i} Inner: ${j}`);
}
}
This example demonstrates nested loops, where the inner loop runs completely for each iteration of the outer loop.
Break and Continue Statements
The break
statement terminates the loop, while the continue
statement skips the current iteration and moves to the next one.
// Break example
for(let i = 1; i <= 10; i++) {
if(i == 5) {
break;
}
console.log(i);
}
// Continue example
for(let i = 1; i <= 10; i++) {
if(i == 5) {
continue;
}
console.log(i);
}
In the first loop, when i
equals 5, the loop terminates. In the second loop, when i
equals 5, that iteration is skipped.
Example 4: While Loop
let i = 1;
while(i <= 10) {
if(i == 4) {
i++;
continue;
}
console.log(i);
i++;
}
This while
loop continues to execute as long as i
is less than or equal to 10. If i
equals 4, that iteration is skipped.
Example 5: Do-While Loop
let i = 6;
do {
console.log(i);
i++;
} while(i <= 5);
The do-while
loop executes the block of code at least once before checking the condition. In this case, it will log 6 and then exit since the condition is not met.