Loops in JavaScript

Loops are a fundamental concept in programming used to execute a block of code repeatedly based on a condition. JavaScript offers several types of loops such as for, while, and do-while, each serving different purposes depending on the situation.

Types of Loops in JavaScript:

Syntax of Loops:

for loop Syntax


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

Example of for loop in JavaScript:

This example uses a for loop to print numbers from 0 to 4.

Example


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

Output

0
1
2
3
4

while loop Syntax


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

Example of while loop in JavaScript:

This example uses a while loop to print numbers from 0 to 4.

Example


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

Output

0
1
2
3
4

do-while loop Syntax


let i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);

Example of do-while loop in JavaScript:

This example uses a do-while loop to print numbers from 0 to 4. The loop will run at least once even if the condition is initially false.

Example


let i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);

Output

0
1
2
3
4

Key Points on Loops: