Skip to content
BasicsChapter 11 / 47Beginner5 min read

Loops

Learn JavaScript loops, the difference between for, while, do while, for...of and for...in, with break and continue, and when to use each.

On this page

1. What are loops?

LoopWhen to use it
forYou know how many times to run, or you need the index
whileYou do not know how many times, it depends on a condition
do...whileYou must run at least once
for...ofOver the values of an array, string, Map or Set
for...inOver the keys of an object

2. Why does it matter?

Imagine printing the price of 100 products. Writing a separate line for each is impossible. A loop is written once and runs on every item.

Without a loopWith a loop
A separate line for every itemOne block, all the items
More items means more codeThe same code, however much data
A chance of mistakes in every lineLogic in one place, and the fix in one place
Hard to work out a totalThe total updates on every round

3. Where is it used?

Real useLoop
Cart totalfor...of
Table from 1 to 10for
Retry until successwhile
Show a menu, then ask again?do...while
Printing every setting of an objectfor...of + Object.entries()
Stopping as soon as the first match is foundbreak

4. How does it work?

A classic for loop has three parts: start, condition, update.

Cycle of a for loop
Start: let i = 0
Check condition: is i less than 3?
If true, run the body
Update: i++
Back to the condition check, if false the loop ends

break ends the loop immediately. continue skips only the current round and moves on to the next one.

5. Code example

for and while:

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

let attempts = 0;
while (attempts < 3) {
  attempts++;
  console.log(`Attempt ${attempts}`);
}

for...of with arrays and objects:

js
const cart = [
  { name: "Book", price: 800 },
  { name: "Pen", price: 50 },
  { name: "Bag", price: 2500 },
];

let total = 0;
for (const item of cart) {
  total += item.price;
}
console.log(total);

const settings = { theme: "dark", lang: "ur" };
for (const [key, value] of Object.entries(settings)) {
  console.log(`${key}: ${value}`);
}

Output: 3350, theme: dark, lang: ur.

break and continue:

js
const numbers = [4, 7, -1, 9, 12];

for (const n of numbers) {
  if (n < 0) continue;
  if (n > 10) break;
  console.log(n);
}

Output: 4, 7, 9. -1 was skipped, and the loop stopped at 12.

How does the code work?

ItemMeaning
let i = 1; i <= 3; i++Start, condition, update
while (attempts < 3)Keep running while the condition is true
for (const item of cart)The next item on every round, no index needed
Object.entries()Turns an object into an array of [key, value] pairs
continueSkip this round, go to the next
breakEnd the whole loop

Interview tip

"Why should you not run for...in on an array?" Because it gives keys (string indexes), not values, and it can also pick up extra properties that come from the prototype. For arrays, for...of or array methods are better.

6. Common mistakes

Mistake: Creating an infinite loop

Why? The while condition never becomes false because you forgot to update the counter, and the page freezes.

Better: In every while loop, check that there is an update that will make the condition false.

Mistake: Running for...in on an array

Why? You get string indexes instead of values, and sometimes extra properties too.

Better: For arrays, use for...of or array methods like map and filter.

Mistake: Off by one error

Why? Writing i <= arr.length makes the index go out of range on the last round and gives undefined.

Better: In an index loop write i < arr.length, or just use for...of.

Mistake: Trying to break inside forEach

Why? break does not work inside a forEach callback, it throws a SyntaxError.

Better: If you need to stop midway, use for...of + break, or methods like find and some.

7. What to learn before and after

Final quick revision

PointDetail
forWith a count or an index
whileBased on a condition, count unknown
do...whileAt least once
for...ofValues, best for arrays
for...inObject keys
break / continueEnd the loop / skip a round