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
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
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++;
}
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);
do {
// Code to execute
} while (condition);
Top comments (0)