DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on

JavaScript Loops

What is loops?

A loop is used to execute a block of code repeatedly until a specified condition becomes false.

Types of Loops in JavaScript

  • for Loop
  • while loop
  • do while

for loop

The for loop is used when the number of iterations is known before the loop starts.


for (let i = 1; i <= 5; i++) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

while Loop

A while loop executes a block of code repeatedly as long as the given condition is true.


let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

do while Loop

A do...while loop executes the code once before checking the condition.


let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 5);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)