Tutorials › JavaScript Tutorial › JavaScript Loops

JavaScript Loops

12 min read · Lesson 11 of 23

A loop repeats a block of code. Instead of writing the same line fifty times, you write it once and tell JavaScript how many times – or under what condition – to repeat it. Loops are how programs work through lists of products, students, transactions and much more.

The for loop

The classic for loop has three parts inside its brackets, separated by semicolons:

for (start; condition; step) {
  // code to repeat
}
  1. start runs once, before the loop begins – usually creating a counter.
  2. condition is checked before every round; the loop stops when it becomes false.
  3. step runs after every round – usually increasing the counter.
Example JAVASCRIPT
for (let i = 1; i <= 5; i++) {
  console.log(`Lap ${i}`);
}
console.log("Race finished");
Result
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Race finished
Try it Yourself »

You can count in steps other than one, or count backwards:

Example JAVASCRIPT
for (let n = 10; n > 0; n -= 3) {
  console.log(n);
}
Result
10
7
4
1
Try it Yourself »

Looping through an array by index

Arrays (covered in Arrays) have numbered positions starting at 0, which fits a for loop perfectly.

Example JAVASCRIPT
const towns = ["Garissa", "Wajir", "Mandera"];

for (let i = 0; i < towns.length; i++) {
  console.log(`${i + 1}. ${towns[i]}`);
}
Result
1. Garissa
2. Wajir
3. Mandera
Try it Yourself »

The while loop

A while loop repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need.

Example JAVASCRIPT
let savings = 0;
let weeks = 0;

while (savings < 2000) {
  savings += 350;
  weeks++;
}

console.log(`Saved KES ${savings} after ${weeks} weeks`);
Result
Saved KES 2100 after 6 weeks
Try it Yourself »
Warning: Make sure something inside a while loop eventually makes the condition false. If not, you get an infinite loop that freezes the browser tab.

The do...while loop

do...while is like while but checks the condition after each round, so the body always runs at least once.

Example JAVASCRIPT
let attempts = 0;

do {
  attempts++;
  console.log(`Attempt ${attempts}`);
} while (attempts < 2);
Result
Attempt 1
Attempt 2
Try it Yourself »

The for...of loop

for...of is the modern, readable way to go through every value in an array, string or other iterable. You do not need a counter at all.

Example JAVASCRIPT
const prices = [120, 450, 80];
let total = 0;

for (const price of prices) {
  total += price;
}
console.log(`Total: KES ${total}`);

for (const letter of "Lamu") {
  console.log(letter);
}
Result
Total: KES 650
L
a
m
u
Try it Yourself »
Tip: Use for...of whenever you need each value and not the index. It is shorter and impossible to get "off by one".

The for...in loop

for...in loops over the property names (keys) of an object.

Example JAVASCRIPT
const scores = { Akinyi: 88, Baraka: 74, Chebet: 91 };

for (const student in scores) {
  console.log(`${student}: ${scores[student]}`);
}
Result
Akinyi: 88
Baraka: 74
Chebet: 91
Try it Yourself »
Note: Do not use for...in on arrays. It gives you the indexes as strings and can include unexpected extra properties. Use for...of or a classic for loop for arrays.

break and continue

  • break exits the loop immediately.
  • continue skips the rest of the current round and moves to the next.
Example JAVASCRIPT
const orders = [300, -1, 450, 0, 999, 200];

for (const amount of orders) {
  if (amount === 999) {
    console.log("Stop code found");
    break;
  }
  if (amount <= 0) {
    continue; // skip invalid amounts
  }
  console.log(`Processing KES ${amount}`);
}
Result
Processing KES 300
Processing KES 450
Stop code found
Try it Yourself »

Nested loops

A loop can sit inside another loop. For every single round of the outer loop, the inner loop runs all the way through. This is how you work with grids, timetables and tables of data. Here we print a small multiplication table:

Example JAVASCRIPT
for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += `${row * col}\t`;
  }
  console.log(line.trimEnd());
}
Result
1	2	3
2	4	6
3	6	9
Try it Yourself »

The \t inserts a tab character to line the numbers up. Be careful with nested loops over big lists: an outer loop of 1,000 rounds with an inner loop of 1,000 rounds runs the inner code a million times.

Which loop should I use?

LoopBest for
forA known number of repetitions, or when you need the index
whileRepeating until something changes, count unknown
do...whileLike while, but must run at least once
for...ofEvery value of an array or string
for...inEvery key of an object

Arrays also have their own looping methods such as forEach and map, which you will meet in Array Methods.

Exercise

Complete the loop so it prints the numbers 0 to 4.

for (let i = 0; i  5; i) {
  console.log(i);
}
Exercise

Loop over every value in the array.

for (const fruit  fruits) {
  console.log(fruit);
}
Sign in or create a free account to track progress, earn XP, badges and a certificate.