Loop
A loop is used to execute a block of code repeatedly until a condition becomes false.
1. for loop - The for loop is the most commonly used loop. It is useful when you know how many times the loop should run.
2. while loop - The while loop executes as long as the condition is true.
3. do while loop - The do...while loop executes the code at least once, even if the condition is false.
**for loop**
for (let i = 1; i <= 5; i++) {
console.log(i);
} // Output:
1
2
3
4
5
**while loop**
let i = 0;
while (i < 10) {
i++;
if (i === 3) continue; // Skips printing 3
if (i === 6) break; // Stops the loop completely at 6
console.log(i);
} // Output:
1
2
4
5
6
**do while loop**
let i = 1;
do {
console.log(i);
i++;
} while (i >= 5); // Output: 1
- break - Stops the loop immediately.
- continue - Skips the current iteration and moves to the next one.
Top comments (0)