Loops in JavaScript
Loops allow you to run a block of code repeatedly. JavaScript supports several loop types including for
, while
, and do...while
.
🔁 1. for
Loop
A concise loop structure often used when the number of iterations is known.
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}
This prints numbers from 1 to 5.
🔄 2. while
Loop
Repeats a block of code as long as a condition is true.
let count = 1;
while (count <= 3) {
console.log("Count:", count);
count++;
}
Runs until count
exceeds 3.
🔁 3. do...while
Loop
Executes the block once before checking the condition.
let num = 1;
do {
console.log("Number:", num);
num++;
} while (num <= 2);
⚠️ The
do...while
loop always runs at least once, even if the condition is false.
📌 When to Use Each Loop
- for – Best for counting loops (e.g., iterate from 1 to 10)
- while – Use when condition should be checked before each iteration
- do...while – Use when the code must run at least once
✅ Tip: Always ensure your loop has a terminating condition to avoid infinite loops.