LearnFrenzy
Sign in Take a free test

Operators and Control Flow · Lesson 8 of 40

JavaScript Loops: for, while, for...of and for...in

4 min read Updated Nov 7, 2026 Saurabh Samir

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 for loop
  • while and do...while
  • for...of vs for...in
  • break, continue and labels

The for loop

for (let i = 1; i <= 5; i++) {
  console.log(`7 x ${i} = ${7 * i}`);
}

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

for (init; condition; update)

  1. initlet i = 1 – runs once
  2. conditioni <= 5? false → leave the loop
  3. bodyruns when the condition is true
  4. 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);

Output

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

Output

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

Output

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

Output

apples 40
bananas 0
cherries 12
bananas out of stock
for...offor...in
Gives youvalueskeys (as strings)
Works oniterables: arrays, strings, Map, Setobjects (including inherited enumerable keys)
Use for arrays?yesno – 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
    }
  }
}

Output

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

  1. 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(" "));

    Output

    1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
  2. 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);

    Output

    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 for for index-based loops; while when the count is unknown; do...while runs at least once.
  • for...of iterates values of arrays, strings, Maps and Sets; for...in iterates object keys.
  • break exits, continue skips, labels exit nested loops.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links