Automate repetitive work with for, while, and
do...while — and control the flow mid-loop with
break and continue.
Loops in JavaScript execute a block of code repeatedly as
long as a specified condition remains true. They automate
repetitive tasks and eliminate code duplication — instead of writing
console.log(1) through console.log(100), one loop
handles all of it.
JavaScript provides three loop types — for, while,
and do...while — plus break and continue
to control what happens mid-loop.
Instead of writing the same code again and again, loops say: "Do this work multiple times until the condition fails."
// Structure: for (initialise; condition; update)
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Count down
for (let i = 5; i >= 1; i--) {
console.log(i);
}
let i = 1) — sets the counter before the loop startsi <= 5) — checked before each iteration; loop stops when falsei++) — runs after each iteration to move the counter forwardlet i = 1;
while (i <= 3) {
console.log("Round " + i);
i++; // must update — otherwise infinite loop!
}
// while: condition checked BEFORE each run
// if false from the start, the body never runs
let count = 10;
while (count < 5) {
console.log("This never prints");
count++;
}
console.log("Loop skipped — condition was false from start");
while when the number of iterations is not known in advancelet i = 1;
do {
console.log("Run " + i);
i++;
} while (i <= 3);
// Key difference: runs at least ONCE even if condition is false
let x = 100;
do {
console.log("Runs once even though x > 5");
x++;
} while (x < 5);
for and while, but essential when the first run must always happen// continue — skip current iteration, keep going
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // skip 3
console.log(i);
}
// Output: 1, 2, 4, 5
// break — exit the loop entirely
for (let i = 1; i <= 10; i++) {
if (i === 4) break; // stop at 4
console.log(i);
}
// Output: 1, 2, 3
continue skips the rest of the current iteration and jumps straight to the next onebreak exits the loop immediately — no further iterations runfor, while, and do...whilelet fruits = ["Apple", "Banana", "Mango", "Grapes"];
// Classic for loop with index
for (let i = 0; i < fruits.length; i++) {
console.log(i + ": " + fruits[i]);
}
// Modern for...of — cleaner when index not needed
for (let fruit of fruits) {
console.log(fruit.toUpperCase());
}
for loop with array.length is the most universal way to iterate an arrayfor...of gives you each element directly — use it when you don't need the indexi < array.length (not <=) — the last valid index is length - 1Think of a washing machine — its cycle maps perfectly to loop concepts:
Click ▶ Preview, enter a range, and watch a loop generate every number — with even numbers highlighted in yellow.
<!DOCTYPE html>
<html>
<head><title>Loops Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">
<h2>Print Numbers</h2>
<label>From:
<input id="from" type="number" value="1"
style="width:70px;padding:6px 10px;border:1px solid #ccc;
border-radius:6px;font-size:1rem;margin:0 8px">
</label>
<label>To:
<input id="to" type="number" value="10"
style="width:70px;padding:6px 10px;border:1px solid #ccc;
border-radius:6px;font-size:1rem;margin:0 8px">
</label>
<button onclick="printNums()"
style="padding:8px 18px;background:#f7df1e;border:none;border-radius:6px;
cursor:pointer;font-weight:700;font-size:1rem">
Show
</button>
<div id="output"
style="margin-top:16px;display:flex;flex-wrap:wrap;gap:8px">
</div>
<script>
function printNums() {
let from = Number(document.getElementById("from").value);
let to = Number(document.getElementById("to").value);
let out = document.getElementById("output");
if (from > to || to - from > 200) {
out.innerHTML = "<b style='color:red'>Enter a valid range (max 200 numbers).</b>";
return;
}
let html = "";
for (let i = from; i <= to; i++) {
let isEven = i % 2 === 0;
html += `<span style="display:inline-block;width:38px;height:38px;
line-height:38px;text-align:center;border-radius:8px;font-weight:600;
background:${isEven ? '#f7df1e' : '#e2e8f0'};
color:${isEven ? '#111' : '#444'}">${i}</span>`;
}
out.innerHTML = html;
}
</script>
</body>
</html>
// Use a for loop to print 1 through 10
for (let i = 1; i <= 10; i++) {
// your code here
}
console.log(i)for (let i = 1; i <= 20; i++) {
// print only even numbers
}
i % 2 === 0 to check if a number is even — if not, continue to skip itfor (let i = 1; i <= 3; i++) {
console.log(i);
}
i = 1 and runs while i <= 3 — that's iterations for 1, 2, and 3. When i becomes 4, the condition is false and the loop stops.
let x = 100;
do {
console.log("Ran once!");
x++;
} while (x < 5);
do...while runs its body first and checks the condition after. Even though x = 100 fails x < 5 immediately, the body still executes once.
break do inside a loop?
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
break exits the loop immediately — no further iterations run. Here, 1 and 2 print but when i === 3 the loop stops entirely. continue would only skip 3 and carry on to 4 and 5.
Choose the right loop for the job — matching the loop to the situation makes your intent clear:
// for — known count
for (let i = 0; i < 5; i++) console.log("Step", i);
// while — unknown count (keep going until condition changes)
let attempts = 0;
while (attempts < 3) {
console.log("Attempt", attempts + 1);
attempts++;
}
// for...of — iterate array values cleanly
let names = ["Aman", "Priya", "Raj"];
for (let name of names) console.log("Hello,", name);
Always avoid infinite loops — if the condition never becomes false, the browser will freeze. Always ensure your loop counter updates:
// ✗ Dangerous — i never changes, runs forever
// while (i <= 5) { console.log(i); } // commented out to be safe
// ✓ Safe — i increments every iteration
let i = 1;
while (i <= 5) {
console.log(i);
i++; // critical — this ends the loop
}
Use continue to write filter logic inside loops — it's often cleaner than nesting an if block around everything:
// Print only numbers divisible by 3 in range 1–15
for (let i = 1; i <= 15; i++) {
if (i % 3 !== 0) continue; // skip non-multiples of 3
console.log(i); // only 3, 6, 9, 12, 15 reach here
}
Use break with a search pattern — exit as soon as you find what you're looking for instead of running unnecessary iterations:
let scores = [72, 88, 55, 95, 61];
let target = 95;
let found = false;
for (let i = 0; i < scores.length; i++) {
if (scores[i] === target) {
console.log("Found " + target + " at index " + i);
found = true;
break; // no point checking the rest
}
}
if (!found) console.log("Not found");
continue skips certain numbers — predict exactly which numbers
will print before running.
for (let i = 1; i <= 5; i++) {
if (i % 2 === 0) continue;
console.log(i);
}
// Loop runs for i = 1, 2, 3, 4, 5
// i = 1: 1 % 2 = 1 (not 0) → condition false → continue NOT triggered
// console.log(1) → prints 1
// i = 2: 2 % 2 = 0 → condition true → continue triggered
// Rest of body skipped → 2 is NOT printed
// i = 3: 3 % 2 = 1 → condition false → continue NOT triggered
// console.log(3) → prints 3
// i = 4: 4 % 2 = 0 → condition true → continue triggered
// 4 is NOT printed
// i = 5: 5 % 2 = 1 → condition false → continue NOT triggered
// console.log(5) → prints 5
// Final output:
// 1
// 3
// 5 ← only the ODD numbers
// Key takeaway:
// i % 2 === 0 is true for EVEN numbers (2, 4)
// continue skips the rest of the iteration for those numbers
// So only ODD numbers (1, 3, 5) reach console.log