DEV Community

M Ramavel
M Ramavel

Posted on

JavaScript Loop

Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient.

Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can use a loop to automate the task and execute it based on the given condition.

For loop

for (initialization; condition; increment/decrement)
{
    // Code to execute
}
Enter fullscreen mode Exit fullscreen mode


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

while-loop

The while loop executes as long as the condition is true. It can be thought of as a repeating if statement.


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

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.


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

do {
// Code to execute
} while (condition);

Top comments (0)