Loops

Topic 4 of 5 in Operators & control flow8 min readBeginnerFree course

Overview

Loops run a block of code again and again. Without them, printing the numbers 1 to 100 would take 100 lines. With a loop, it takes three:

JavaScript
for (let i = 1; i <= 100; i++) {
  console.log(i);
}

Each pass through a loop’s body is called an iteration. JavaScript has several kinds of loop; each suits a different job.

The for loop

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

The brackets hold three parts, separated by semicolons:

  1. Start — let i = 1 runs once, before anything else. It creates the loop’s counter.
  2. Check — i <= 3 is tested before each iteration. If it’s false, the loop ends.
  3. Update — i++ runs after each iteration, moving the counter on.

The for loop for (let i = 1; i <= 3; i++) with its parts labelled. Step 1, let i = 1, runs once. Step 2, the check i <= 3, runs before each lap; if true, step 3 runs the body, then step 4, i++, runs and the loop goes back to the check. When the check is false, the loop ends.

The counter can count in any direction and by any step:

JavaScript
for (let i = 10; i > 0; i--) { /* 10, 9, … 1 */ }
for (let i = 0; i <= 100; i += 10) { /* 0, 10, 20, … 100 */ }

Looping over an array by index

Arrays are numbered from 0, so the classic pattern starts at 0 and stops before length:

JavaScript
const colours = ['red', 'green', 'blue'];
for (let i = 0; i < colours.length; i++) {
  console.log(i, colours[i]);
}

Writing i <= colours.length is a common off-by-one mistake: the last iteration reads colours[3], which is undefined.

while and do…while

while repeats as long as a condition is true — useful when you don’t know how many rounds you’ll need:

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

A more realistic example: keep halving a number until it’s small enough.

JavaScript
let size = 1000;
let steps = 0;
while (size > 1) {
  size /= 2;
  steps++;
}
console.log(steps); // 10

do…while always runs at least once, because it checks the condition at the end:

JavaScript
let answer;
do {
  answer = prompt('Type yes to continue');
} while (answer !== 'yes');

Infinite loops

If a loop’s condition never becomes false, it runs forever and freezes the page:

JavaScript
let i = 0;
while (i < 5) {
  console.log(i); // i never changes — infinite loop!
}

Every while loop must change something that its condition depends on. If your browser tab locks up while you’re practising, an infinite loop is the usual suspect — close the tab and check your update step.

for…of

The easiest way to loop over the values of an array (or the characters of a string):

JavaScript
const topics = ['Loops', 'Functions', 'Objects'];
for (const topic of topics) {
  console.log(topic);
}

for (const char of 'hey') {
  console.log(char); // 'h', 'e', 'y'
}

for…of works with anything iterable — arrays, strings, Maps, Sets and more (you’ll see how in Iterators and generators). Use const for the loop variable, since each iteration gets a fresh one.

Need the index too? Use entries() with destructuring:

JavaScript
for (const [index, topic] of topics.entries()) {
  console.log(`${index + 1}. ${topic}`);
}

for…in

for…in loops over an object’s keys:

JavaScript
const scores = { asha: 9, ravi: 7 };
for (const name in scores) {
  console.log(name, scores[name]);
}
// asha 9
// ravi 7

Don’t use for…in on arrays. It gives you indexes as strings and can include extra properties. Use for…of instead.

For objects, many developers prefer Object.entries() with for…of, which gives you the key and value together:

JavaScript
for (const [name, score] of Object.entries(scores)) {
  console.log(name, score);
}

break and continue

break stops the loop immediately. continue skips the rest of the current iteration and moves on to the next:

JavaScript
for (const n of [1, 2, 3, 4, 5]) {
  if (n === 2) continue; // skip 2
  if (n === 4) break;    // stop at 4
  console.log(n);        // 1, 3
}

break is ideal for searching — stop as soon as you’ve found what you need:

JavaScript
const users = ['ravi', 'asha', 'mina'];
let found = false;
for (const user of users) {
  if (user === 'asha') {
    found = true;
    break; // no need to check 'mina'
  }
}

Nested loops

A loop inside a loop runs the inner loop completely for every iteration of the outer one — useful for grids and tables:

JavaScript
for (let row = 1; row <= 3; row++) {
  let line = '';
  for (let col = 1; col <= 3; col++) {
    line += `${row * col}\t`;
  }
  console.log(line);
}
// 1  2  3
// 2  4  6
// 3  6  9

break and continue only affect the innermost loop. To break out of an outer loop, give it a label: outer: for (…) { … break outer; }. Labels are rare; often moving the loops into a function and using return is clearer.

Which loop should I use?

You want to… Use
Repeat a known number of times, or count for
Go through each item in an array or string for…of
Repeat until something changes, count unknown while
Run at least once, then maybe repeat do…while
Go through an object’s keys for…in or Object.keys()

You’ll also meet array methods such as forEach, map and filter in the Arrays chapter. They replace many loops with something shorter and clearer.

Exercise

Sum the even numbers

Write sumEvens(n) that adds up every even number from 1 to n. Then write countdown(n) that returns an array counting down from n to 1.

JavaScript
function sumEvens(n) {
  // your code here
}

function countdown(n) {
  // your code here
}

sumEvens(10);  // 30
countdown(3);  // [3, 2, 1]

Summary

  • for is best when you know how many times to repeat: start, check, update.
  • while repeats while a condition holds; do…while always runs at least once.
  • for…of loops over the values of arrays, strings and other iterables.
  • for…in loops over an object’s keys — don’t use it on arrays.
  • break stops a loop; continue skips to the next round. Make sure every loop can end.