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
forloop - When to use
whileanddo...while - Looping through arrays with
for...of - Looping through object keys with
for...in - Controlling loops with
breakandcontinue
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
forloop has three parts: start (let i = 1), condition checked before each round (i <= 5) and step run after each round (i++). - Use
forwhen you know how many times to repeat. Usewhilewhen you only know the stopping condition, as in the savings example, where the number of years is the answer. do...whilechecks its condition after the body, so it always runs at least once. Here it runs once even thoughn < 0is false from the start.- Every
whileloop 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...ofgives each value of an array (or string, Map or Set). It is the clearest way to visit every item.for...ingives each key of an object. Do not use it on arrays: it yields the indexes as strings and can include extra properties.continueskips the rest of the current round and moves to the next one.breakleaves 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?
| Loop | Best for |
|---|---|
for (let i = 0; ...) | Counting, or when you need the index |
for...of | Every value in an array or string |
for...in | Every key in a plain object |
while | Repeat until something happens |
do...while | Run at least once, then check |
array.forEach() | Running a function for each item (see arrays) |
Common Mistakes
- Infinite loops, for example forgetting
i++or changing the wrong variable. - Off-by-one errors: arrays start at index 0, so loop with
i < arr.length, not<=. - Using
for...inon an array instead offor...of. - Declaring the counter with
var, which leaks it outside the loop. Uselet.
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
forcounts;whilerepeats until a condition fails;do...whileruns at least once.for...ofvisits values;for...invisits object keys.continueskips one round;breakends the loop.
Next: JavaScript Functions.
