🔁 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

Loop TypeUsed When
do...whileWhen you want to execute once before checking condition
whileWhen condition-based repetition is needed
forWhen number of iterations is known

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);
}

💡 Quick Practice

  1. Exercises Set

Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR