🔁 Loops in JavaScript
Last Updated: Jan 2026
Loops allow us to repeat a block of code multiple times until a condition is met. They make our code short, clean, and powerful.
Why Use Loops?
Without loops 👇
printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");
With loops 👇
for (int i = 0; i < 5; i++) {
printf("Hello");
}
💡 Less code, same result.
🧭 Types of Loops in JavaScript
do...while Loop
It will run once, even if the condition is false — because the condition is checked after the loop body.
Syntax:
do {
// loop body
} while (condition);
Example:
int i = 0;
do {
printf("%d\n",i);
i++;
} while (i < 5);
💡 Output: Runs once (even though condition is false).
while Loop
Repeats while the condition is true.
Syntax:
while (condition) {
// loop body
}
Example:
int i = 1;
while (i <= 5) {
printf("Count: %d\n", i);
i++;
}
for Loop
Repeats a specific number of times.
Syntax:
for (initialization; condition; update) {
// code block
}
Example:
for (int i = 1; i <= 5; i++) {
printf("Number: %d\n", i);
}
