DEV Community

Cover image for Loops concept in JavaScript
Raghul
Raghul

Posted on

Loops concept in JavaScript

JavaScript Loops

Loops in JavaScript allow a block of code to run multiple times as long as a given condition is satisfied. They help reduce repetition and make programs more efficient and organized. Loops offer a quick and easy way to do something repeatedly. Loops can execute a block of code a number of times. Loops continue running until the condition becomes false.

*In JavaScript, there are three types of Loops : *

1. for Loop
A for loop repeats until a specified condition evaluates to false. The for loop repeats a block of code a specific number of times. It contains initialization, condition, and increment/decrement in one line. The for statement creates a loop with 3 optional expressions:

for (expr1; expr2; expr3) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode
  • exp1 is executed one time before the execution of the code block.
  • exp2 defines the condition for executing the code block.
  • exp3 is executed every time the code block has been executed.

2. while Loop
The while loop executes as long as the condition is true. It can be thought of as a repeating if statement. The while loop loops through a block of code as long as a specified condition is true.


let i = 0;
while (i < 3) {
    console.log("Number:", i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

3. do-while Loop
The do-while loop is similar to while loop except it executes the code block at least once before checking the condition. The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


let i = 0;
do {
    console.log("Iteration:", i);
    i++;
} while (i < 3);
Enter fullscreen mode Exit fullscreen mode
  • The do while runs at least once, even if the condition is false from the start.
  • This is because the code block is executed before the condition is tested.

Top comments (0)