Loops

JavaScript · Lesson 14 of 61 6 min read Updated

Imagine printing the 7 times table, sending a reminder to every student in a class of 60, or adding up a month of daily expenses. Writing the same line again and again is slow and error-prone. A loop runs a block of code many times for you.

In this lesson you will learn the three classic loops in JavaScript (for, while and do...while), how to stop a loop early or skip a step, and how to avoid the dreaded infinite loop.

The for loop

A for loop is best when you know how many times to repeat. Its first line has three parts, separated by semicolons.

JavaScriptRun it yourself
for (let i = 1; i <= 10; i++) {
  console.log(`7 x ${i} = ${7 * i}`);
}
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

Read the first line in three steps:

  1. let i = 1 runs once at the start and creates a counter variable.
  2. i <= 10 is checked before every round. If it is true, the block runs; if false, the loop ends.
  3. i++ runs after every round and adds 1 to the counter.

Each round of a loop is called an iteration. The counter is traditionally called i (for "index"). It must use let, not const, because it changes.

Looping over a list by index

Lists in JavaScript are called arrays, and each item has an index starting at 0. A for loop can visit every index from 0 up to length - 1:

JavaScriptRun it yourself
const stations = ["Rohtak", "Sampla", "Bahadurgarh", "Delhi"];

for (let i = 0; i < stations.length; i++) {
  console.log(`Stop ${i + 1}: ${stations[i]}`);
}
Output
Stop 1: Rohtak
Stop 2: Sampla
Stop 3: Bahadurgarh
Stop 4: Delhi

Note the < in i < stations.length. With 4 stations, the indexes are 0, 1, 2 and 3. Writing <= would try index 4, which does not exist. When you just need each item and not its index, the simpler for...of loop is better; you will learn it in for...of and for...in. Arrays themselves are covered in Arrays.

The while loop

A while loop is best when you do not know in advance how many rounds you need. It keeps going as long as its condition is true.

JavaScriptRun it yourself
const goal = 10000;
let savings = 0;
let months = 0;

while (savings < goal) {
  savings += 1500;
  months++;
}

console.log(`Goal reached in ${months} months with ₹${savings}`);
Output
Goal reached in 7 months with ₹10500

Priya saves ₹1,500 a month. The loop does not know it needs 7 rounds; it simply checks savings < goal before each round and stops when the answer is false.

Something inside a while loop must change the condition eventually. If savings never grew, the condition would stay true forever.

The do...while loop

A do...while loop checks its condition after each round, so the block always runs at least once.

JavaScriptRun it yourself
let number = 0;
let digits = 0;

do {
  digits++;
  number = Math.floor(number / 10);
} while (number > 0);

console.log("Digits:", digits);
Output
Digits: 1

This counts the digits of a number by removing the last digit (dividing by 10) until nothing is left. The number 0 still has one digit. A plain while (number > 0) loop would never run for 0 and report 0 digits; do...while gets it right. Change number to 40213 and run it again.

do...while is the least used loop, but it fits any task of the form "do this once, then repeat while needed".

break and continue

Two keywords change the flow inside any loop:

  • break stops the loop completely and jumps to the code after it.
  • continue skips the rest of the current round and moves to the next one.
JavaScriptRun it yourself
const scores = [45, 0, 78, 102, 12];

for (let i = 0; i < scores.length; i++) {
  if (scores[i] === 0) {
    console.log("Out for a duck, skipping");
    continue;
  }
  if (scores[i] >= 100) {
    console.log(`Century found: ${scores[i]}`);
    break;
  }
  console.log(`Score: ${scores[i]}`);
}
Output
Score: 45
Out for a duck, skipping
Score: 78
Century found: 102

The 0 triggered continue, so its "Score" line was skipped. The 102 triggered break, so the loop ended and the last score, 12, was never visited. break is useful when searching: once you find what you need, there is no point checking the rest.

Infinite loops

A loop whose condition never becomes false runs forever. The browser tab freezes, and after a while the browser offers to stop the page.

JavaScript
let tickets = 5;
while (tickets > 0) {
  console.log("Selling a ticket");
  // forgot: tickets--;
}

If this happens while you are practising, close the tab and fix the code. Before you run any loop, ask: "What changes each round, and when does the condition become false?"

Which loop should I use?

LoopBest whenExample
forYou know the number of roundsPrint a times table, count from 1 to 100
whileYou repeat until something happensSave until a goal, retry until success
do...whileThe block must run at least onceShow a menu, then repeat on request
for...ofYou visit every item of a listPrint every student's name

In modern code you will also loop over arrays with methods like forEach() and map(), covered in Array Methods.

Common mistakes

  • Off-by-one errors. Indexes go from 0 to length - 1, so use i < list.length, not <=.
  • const for the counter. for (const i = 0; i < 5; i++) fails on i++. Use let.
  • Forgetting to change the condition in a while loop. The loop never ends.
  • A semicolon after the loop line. for (let i = 0; i < 5; i++); runs an empty loop five times, and the block below runs once.

Key points

  • A for loop has a start, a condition and an update, and suits a known number of rounds.
  • A while loop repeats while its condition is true and suits an unknown number of rounds.
  • A do...while loop always runs its block at least once.
  • break exits a loop; continue skips to the next round.
  • Every loop needs a condition that eventually becomes false.

Exercise

A shop in Lucknow has 20 laddoos. Customers buy 3 at a time. Use a while loop to sell to customers until fewer than 3 laddoos are left, printing "Customer 1 bought 3, 17 left" and so on. After the loop, print how many laddoos are left over.

Show solution
JavaScript
let laddoos = 20;
let customer = 0;

while (laddoos >= 3) {
  laddoos -= 3;
  customer++;
  console.log(`Customer ${customer} bought 3, ${laddoos} left`);
}

console.log("Left over:", laddoos);
Output
Customer 1 bought 3, 17 left
Customer 2 bought 3, 14 left
Customer 3 bought 3, 11 left
Customer 4 bought 3, 8 left
Customer 5 bought 3, 5 left
Customer 6 bought 3, 2 left
Left over: 2

A while loop fits because you do not decide the number of customers in advance; the stock decides it. laddoos -= 3 changes the condition, so the loop ends.

Quick Quiz

1. How many times does for (let i = 0; i < 5; i++) run its block?

2. Which loop always runs its block at least once?

3. What does continue do inside a loop?

Learn JavaScript with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call