Skip to content
Laviyx Learn

Try

JavaScript course menu

JavaScript Loops: for, while and do...while with Examples

Learn JavaScript loops: the for loop (initialisation, condition, update), counting up and down, looping over arrays by index, while loops for unknown repeat counts, do...while, infinite loops, nested loops, and choosing the right loop.

Beginner7 min readUpdated
On this page

Loops repeat code. Instead of writing the same statement ten times, you write it once and tell JavaScript how many times, or until when, to repeat it.

The for loop#

JavaScript
for (let i = 1; i <= 5; i++) {
  console.log(`Lap ${i}`);
}
Output
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5

The three parts in the parentheses, separated by semicolons:

  1. Initialisation (let i = 1): runs once, before the loop starts.
  2. Condition (i <= 5): checked before each repetition; the loop stops when it is false.
  3. Update (i++): runs after each repetition.

Counting in other ways#

JavaScript
for (let i = 10; i > 0; i -= 3) {
  console.log(i);
}
Output
10
7
4
1

Looping over an array by index#

JavaScript
const fruits = ["mango", "banana", "guava"];
for (let i = 0; i < fruits.length; i++) {
  console.log(`${i + 1}. ${fruits[i]}`);
}
Output
1. mango
2. banana
3. guava

Indexes start at 0, so the condition is i < fruits.length, not <=. When you do not need the index, the simpler for...of loop is better.

Building a result#

JavaScript
let total = 0;
for (let n = 1; n <= 100; n++) {
  total += n;
}
console.log(total);
Output
5050

The while loop#

while repeats as long as a condition is true. Use it when you do not know in advance how many repetitions you need:

JavaScript
let savings = 1000;
let months = 0;

while (savings < 2000) {
  savings *= 1.1;   // grows 10% a month
  months++;
}
console.log(`${months} months, savings ₹${savings.toFixed(2)}`);
Output
8 months, savings ₹2143.59

do...while#

do...while checks the condition after each repetition, so the body always runs at least once:

JavaScript
let attempts = 0;
let number;

do {
  attempts++;
  number = attempts * 7;          // stand-in for "get the next value"
} while (number % 5 !== 0);

console.log(`Found ${number} after ${attempts} attempts`);
Output
Found 35 after 5 attempts

It suits "do something, then decide whether to repeat", such as asking for input until it is valid.

Infinite loops#

If the condition never becomes false, the loop never ends and the page or program freezes:

JavaScript
let i = 0;
while (i < 5) {
  console.log(i);
  // forgot i++ : i is always 0, so this runs forever
}

Make sure something in the loop moves it towards its end. If a browser tab freezes, close it; in Node.js, press Ctrl+C.

Nested loops#

A loop inside another loop runs completely for every repetition of the outer one:

JavaScript
for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 4; col++) {
    line += `${row * col}`.padStart(4);
  }
  console.log(line);
}
Output
   1   2   3   4
   2   4   6   8
   3   6   9  12

Which loop?#

SituationLoop
Known number of repetitions, or you need the indexfor
Every item in an array or stringfor...of
Repeat until a condition changeswhile
Run at least once, then checkdo...while
Transform or filter an arrayArray methods such as map and filter (Array Methods)

Practice#

Practice exercise

Print the multiplication table of 7 from 7 x 1 = 7 to 7 x 10 = 70, then use a while loop to find the smallest power of 2 that is greater than 1000.

Show solution
JavaScript
for (let i = 1; i <= 10; i++) {
  console.log(`7 x ${i} = ${7 * i}`);
}

let power = 1;
while (power <= 1000) {
  power *= 2;
}
console.log(power);
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
1024

Key takeaway#

Finished this lesson?