JavaScript Loops

JavaScript loops repeat a block of code. Instead of writing the same statement ten times, you write it once and let a loop run it as many times as needed.

The for Loop

A for loop has three parts: a start value, a condition checked before each run, and an update after each run.

for (let i = 1; i <= 5; i++) {
  console.log("Step", i);
}
Step 1
Step 2
Step 3
Step 4
Step 5

while and do...while

while repeats as long as its condition is true; use it when you do not know the number of iterations upfront. do...while always runs its body at least once because the condition is checked after.

let balance = 100;
let years = 0;
while (balance < 200) {
  balance *= 1.1;
  years++;
}
console.log("Doubled after", years, "years");

let n = 10;
do {
  console.log("Runs once even though n > 5:", n);
} while (n < 5);
Doubled after 8 years
Runs once even though n > 5: 10

for...of: Loop Over Values

for...of iterates the values of any iterable: arrays, strings, Maps and Sets. It is the cleanest way to loop over an array.

const cities = ["Lahore", "Dubai", "London"];
for (const city of cities) {
  console.log(city.toUpperCase());
}
for (const ch of "JS") console.log(ch);
LAHORE
DUBAI
LONDON
J
S

for...in: Loop Over Object Keys

for...in iterates the property names of an object. Do not use it for arrays; use for...of or array methods instead.

const book = { title: "Clean Code", pages: 464 };
for (const key in book) {
  console.log(key, "=", book[key]);
}
title = Clean Code
pages = 464

break and continue

break exits the loop completely. continue skips the rest of the current iteration and moves to the next one.

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue; // skip even numbers
  if (i > 7) break;          // stop after 7
  console.log(i);
}
1
3
5
7

Frequently asked questions

What is the difference between for...of and for...in?

for...of gives you the values of an iterable like an array. for...in gives you the keys (property names) of an object.

How do I avoid an infinite loop?

Make sure the loop condition eventually becomes false, for example by updating the counter inside the loop. If the browser freezes, close the tab.

Is forEach better than a for loop?

forEach is concise for arrays, but you cannot break out of it or use await inside it sequentially. for...of supports both.