Operators and Control Flow · Lesson 8 of 40
JavaScript Loops: for, while, for...of and for...in
A loop repeats code: process every order, retry a request three times, print a times table. JavaScript has the classic C-style for, while and do...while, plus for...of for iterating values. Choosing the right loop makes intent obvious.
In this lesson
- The classic
forloop whileanddo...whilefor...ofvsfor...inbreak,continueand labels
The for loop
for (let i = 1; i <= 5; i++) {
console.log(`7 x ${i} = ${7 * i}`);
}
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
for (init; condition; update)
- initlet i = 1 – runs once
- conditioni <= 5? false → leave the loop
- bodyruns when the condition is true
- updatei++ then back to the condition
Use the classic for when you need the index, want to step by something other than 1, or loop backwards:
const word = "LEARN";
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
NRAEL
while and do...while
Use while when you don't know in advance how many times to loop:
let balance = 10000;
let years = 0;
while (balance < 20000) {
balance *= 1.08; // 8% growth per year
years++;
}
console.log(`Doubled after ${years} years: ₹${Math.round(balance)}`);
let attempt = 0;
do {
attempt++;
console.log("Attempt", attempt);
} while (attempt < 2); // the body always runs at least once
Doubled after 10 years: ₹21589 Attempt 1 Attempt 2
Common mistake: infinite loops
If the condition can never become false – for example you forget years++ or balance *= … – the loop runs forever and freezes the browser tab. Always make sure something in the body moves toward the exit.
for...of: loop over values
for...of works on any iterable – arrays, strings, Maps, Sets – and is the most readable choice when you just need each value:
const cart = [
{ item: "Notebook", price: 60 },
{ item: "Pen", price: 20 },
{ item: "Bag", price: 899 },
];
let total = 0;
for (const { item, price } of cart) {
console.log(item.padEnd(10, "."), price);
total += price;
}
console.log("Total", total);
for (const [index, fruit] of ["mango", "guava"].entries()) {
console.log(index, fruit);
}
Notebook.. 60 Pen....... 20 Bag....... 899 Total 979 0 mango 1 guava
for...in: loop over keys
for...in loops over an object's property names. For objects, Object.entries() with for...of is usually clearer:
const stock = { apples: 40, bananas: 0, cherries: 12 };
for (const fruit in stock) {
console.log(fruit, stock[fruit]);
}
for (const [fruit, qty] of Object.entries(stock)) {
if (qty === 0) console.log(`${fruit} out of stock`);
}
apples 40 bananas 0 cherries 12 bananas out of stock
for...of | for...in | |
|---|---|---|
| Gives you | values | keys (as strings) |
| Works on | iterables: arrays, strings, Map, Set | objects (including inherited enumerable keys) |
| Use for arrays? | yes | no – keys are strings and order/extra keys can surprise you |
break, continue and labels
const scores = [45, 82, -1, 67, 90];
for (const s of scores) {
if (s < 0) {
console.log("Invalid score, stopping");
break; // leave the loop
}
if (s < 50) continue; // skip to the next iteration
console.log("Passed:", s);
}
outer: for (let r = 1; r <= 3; r++) {
for (let c = 1; c <= 3; c++) {
if (r * c === 4) {
console.log(`Found 4 at row ${r}, col ${c}`);
break outer; // leave both loops
}
}
}
Passed: 82 Invalid score, stopping Found 4 at row 2, col 2
In chapter 6 you'll meet array methods like map, filter and find, which replace many loops with a single, intention-revealing call.
Practice
Try it yourself
Print FizzBuzz for 1–15: "Fizz" for multiples of 3, "Buzz" for 5, "FizzBuzz" for both.
Show solution
const out = []; for (let i = 1; i <= 15; i++) { let s = ""; if (i % 3 === 0) s += "Fizz"; if (i % 5 === 0) s += "Buzz"; out.push(s || i); } console.log(out.join(" "));1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Count the vowels in "JavaScript Developer" using
for...of.Show solution
let vowels = 0; for (const ch of "JavaScript Developer".toLowerCase()) { if ("aeiou".includes(ch)) vowels++; } console.log(vowels);7
Quick check
Which loop always runs its body at least once?
do...while.
What does for...in give you on an array?
The indexes as strings ("0", "1"…) – use for...of for values.
How do you exit two nested loops at once?
Label the outer loop and use break label (or move the loops into a function and return).
Summary
- Classic
forfor index-based loops;whilewhen the count is unknown;do...whileruns at least once. for...ofiterates values of arrays, strings, Maps and Sets;for...initerates object keys.breakexits,continueskips, labels exit nested loops.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.