Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 156 ยท Control Flow

for Loops

Repeat code with the classic JavaScript for loop. Learn its three parts, counting up and down, looping over arrays, nested loops and off-by-one bugs.

Computers are good at doing the same thing many times without getting bored. Print the numbers 1 to 100, add up every price in a cart, draw a row of stars: each of these is one small action repeated. Instead of copying a line of code a hundred times, you write it once inside a loop and let JavaScript repeat it.

JavaScript has several loops. This lesson covers the classic for loop, the one you reach for when you know how many times to repeat, or when you need a counter. You'll learn its three parts, common counting patterns, how to walk through an array by index, how nested loops work, and how to avoid the most common loop bug of all.

The shape of a for loop

A for loop has three parts in its parentheses, separated by semicolons, followed by a body:

JavaScript
for (initialization; condition; update) {
  // body: runs once per repetition
}
  • Initialization runs once, before anything else. It usually creates a counter: let i = 0.
  • Condition is checked before every repetition. If it's truthy, the body runs; if it's falsy, the loop ends.
  • Update runs after every repetition, usually to move the counter: i++.

Each run of the body is called an iteration. Here's the smallest useful example:

JS Counting to five

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step through it in your head:

  1. let i = 1 creates the counter.
  2. Is 1 <= 5? Yes, so the body logs "Iteration number 1".
  3. i++ makes i equal to 2. Is 2 <= 5? Yes, log it. And so on.
  4. After the fifth iteration, i++ makes i equal to 6. Is 6 <= 5? No, so the loop stops and the program moves on.

The name i (short for "index") is a convention, not a rule. Use a descriptive name such as row or page when it helps.

Use let for the counter. It must change on each iteration, so const won't work. And let keeps the counter scoped to the loop: try to log i after the loop above and you'll get a ReferenceError. Each iteration even gets its own copy of i, which matters when you create functions inside loops (see Closures).

Counting patterns

Change the three parts and you get very different sequences:

JS Counting patterns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The 0 to i < 5 pattern is worth memorizing. It runs exactly 5 times, and it lines up perfectly with how arrays are indexed, as you'll see next.

Accumulating a result

A loop often builds up a value over its iterations. Declare a variable before the loop, then update it inside:

JS Sum and product

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Start a sum at 0 and a product at 1. Starting a product at 0 is a classic mistake: every multiplication then gives 0.

Looping over an array

Arrays number their items from 0, and array.length tells you how many there are. So the loop for (let i = 0; i < array.length; i++) visits every index exactly once:

JS Walking through an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The index-based loop gives you full control: you can skip items, go backwards, or look at neighbors such as prices[i - 1]. When you just want each value in order, the simpler for...of loop is usually nicer, and array methods like forEach and map (in map, filter, reduce and forEach) are even more common in modern code.

Off-by-one errors

The single most common loop bug is running one time too many or one time too few. With arrays, the danger is using <= instead of <:

JavaScript
const colors = ["red", "green", "blue"];

for (let i = 0; i <= colors.length; i++) {
  console.log(colors[i]);
}
// red, green, blue, undefined  <- index 3 doesn't exist

colors.length is 3, but the last index is 2. JavaScript doesn't throw an error when you read past the end of an array; it quietly gives you undefined, which can travel a long way before something breaks.

Rule of thumb: start at 0 and use < with .length. If you start at 1, as when counting from 1 to 10 for display, use <=. When unsure, test with a tiny case, like an array of one item, and count the iterations.

Nested loops

A loop's body can contain another loop. For each iteration of the outer loop, the inner loop runs from start to finish. This is how you work with grids, tables and pairs of items.

JS A multiplication table

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The outer loop runs 5 times and the inner loop runs 5 times per outer iteration, so the multiplication happens 25 times. That multiplying effect is worth remembering: two nested loops over 1,000 items each mean a million iterations. Nested loops are fine for small data but can become slow on large data.

Nested loops also work on arrays of arrays. The inner loop can even depend on the outer counter, which is how you build triangles or compare every pair exactly once:

JS Every pair, once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Give nested counters different names. Reusing i in both loops is a bug, and with let the inner i simply hides the outer one, which is confusing to read.

Optional parts

All three parts of the header are optional; only the two semicolons are required. You'll occasionally see a counter declared before the loop, or the update done inside the body:

JavaScript
let attempts = 0;
for (; attempts < 3; ) {
  attempts++;
}

If you leave out the condition, it counts as always true, so for (;;) { } loops forever unless something inside stops it with break (covered in break, continue and Labels). When you find yourself removing parts of a for header, a while loop is usually the clearer choice.

Infinite loops freeze things. If the condition can never become false, for example for (let i = 0; i < 10; i--), the loop never ends. In a normal browser tab, that freezes the page. Our editors have a Stop button, but always double-check that your update moves the counter toward the end.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many times does the body of for (let i = 0; i < 4; i++) run?

    i takes the values 0, 1, 2 and 3. When i becomes 4, the condition 4 < 4 is false and the loop ends.
  2. 2. In which order do the parts of a for loop run?

    Initialization runs once; then each iteration checks the condition, runs the body and finally runs the update.
  3. 3. An array has 3 items. What goes wrong with for (let i = 0; i <= arr.length; i++)?

    The last valid index is length - 1. With <= the loop also visits index 3, which does not exist, so you get undefined.
  4. 4. An outer loop runs 10 times and an inner loop runs 20 times per outer iteration. How many times does the inner body run?

    The inner loop runs completely for each outer iteration: 10 ร— 20 = 200.
  5. 5. Why should a running product start at 1 instead of 0?

    1 is the neutral value for multiplication, just as 0 is for addition.

Summary

  • A for loop has three parts: initialization (once), condition (before each iteration) and update (after each iteration).
  • for (let i = 0; i < n; i++) runs exactly n times and matches array indexes 0 to length - 1.
  • Count down with i--, step with i += 5, and build results in variables declared before the loop.
  • Off-by-one errors are common; with arrays, use < and .length.
  • Nested loops multiply: the inner loop runs fully for every outer iteration.
  • Make sure the condition can become false, or the loop never ends.

Next: while and do...while โ€” loops that run until a condition changes, however many steps that takes.