DEV Community

Pranay Rebeyro
Pranay Rebeyro

Posted on

Loops in JavaScript

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
Enter fullscreen mode Exit fullscreen mode
**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
Enter fullscreen mode Exit fullscreen mode
**do while loop**
let i = 1;

do {
    console.log(i);
    i++;
} while (i >= 5); // Output: 1
Enter fullscreen mode Exit fullscreen mode
  1. break - Stops the loop immediately.
  2. continue - Skips the current iteration and moves to the next one.

Top comments (0)