Reading history

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

4 min read 2 views

Learn JavaScript loops: for, while, do...while, for...of for arrays, for...in for objects, and controlling loops with break and continue.

A loop repeats a block of code, either a set number of times or until a condition changes. Loops print tables, add up totals, process every item in a list and keep asking for input until it is valid. JavaScript has the classic for, while and do...while loops plus for...of for lists and for...in for object keys.

In this lesson you will learn

  • The three parts of a for loop
  • When to use while and do...while
  • Looping through arrays with for...of
  • Looping through object keys with for...in
  • Controlling loops with break and continue

for, while and do…while

// for loop: start; condition; step
for (let i = 1; i <= 5; i++) {
  console.log("5 x " + i + " = " + 5 * i);
}

// while loop: repeat while the condition is true
let balance = 1000;
let years = 0;
while (balance < 1500) {
  balance *= 1.1;   // 10% growth per year
  years++;
}
console.log("Years needed:", years, "Balance:", balance.toFixed(2));

// do...while runs the body at least once
let n = 0;
do {
  console.log("do...while ran with n =", n);
  n++;
} while (n < 0);

Output

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
Years needed: 5 Balance: 1610.51
do...while ran with n = 0
  • A for loop has three parts: start (let i = 1), condition checked before each round (i <= 5) and step run after each round (i++).
  • Use for when you know how many times to repeat. Use while when you only know the stopping condition, as in the savings example, where the number of years is the answer.
  • do...while checks its condition after the body, so it always runs at least once. Here it runs once even though n < 0 is false from the start.
  • Every while loop must change something that eventually makes the condition false, or it never stops.

for…of, for…in, break and continue

const fruits = ["mango", "jackfruit", "lychee"];
for (const fruit of fruits) {          // values
  console.log("I like", fruit);
}

const prices = { rice: 70, lentils: 120, oil: 190 };
for (const item in prices) {           // keys of an object
  console.log(item, "costs", prices[item], "taka");
}

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue;           // skip even numbers
  if (i > 7) break;                    // stop the loop completely
  console.log("odd:", i);
}

Output

I like mango
I like jackfruit
I like lychee
rice costs 70 taka
lentils costs 120 taka
oil costs 190 taka
odd: 1
odd: 3
odd: 5
odd: 7
  • for...of gives each value of an array (or string, Map or Set). It is the clearest way to visit every item.
  • for...in gives each key of an object. Do not use it on arrays: it yields the indexes as strings and can include extra properties.
  • continue skips the rest of the current round and moves to the next one.
  • break leaves the loop completely. Here the loop stops at 9 before it is printed, so the last odd number shown is 7.

Which Loop Should I Use?

LoopBest for
for (let i = 0; ...)Counting, or when you need the index
for...ofEvery value in an array or string
for...inEvery key in a plain object
whileRepeat until something happens
do...whileRun at least once, then check
array.forEach()Running a function for each item (see arrays)

Common Mistakes

  1. Infinite loops, for example forgetting i++ or changing the wrong variable.
  2. Off-by-one errors: arrays start at index 0, so loop with i < arr.length, not <=.
  3. Using for...in on an array instead of for...of.
  4. Declaring the counter with var, which leaks it outside the loop. Use let.

Practice Exercises

Exercise 1. Add up all the numbers from 1 to 100 with a for loop.

Show answer
let sum = 0;
for (let i = 1; i <= 100; i++) {
  sum += i;
}
console.log(sum); // 5050

Exercise 2. Count how many times the letter “a” appears in “banana bread”.

Show answer
let count = 0;
for (const ch of "banana bread") {
  if (ch === "a") count++;
}
console.log(count); // 4

Frequently Asked Questions

Can I break out of a forEach loop?

No. break does not work inside forEach(). Use a for...of loop, or array methods such as some() or find() that stop early.

How do I loop backwards?

Start at the last index and count down: for (let i = arr.length - 1; i >= 0; i--).

Summary

  • for counts; while repeats until a condition fails; do...while runs at least once.
  • for...of visits values; for...in visits object keys.
  • continue skips one round; break ends the loop.

Next: JavaScript Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *