Please enable JavaScript to use CodeHS

JavaScript Tutorial

For Loops in JavaScript

A for loop runs a block of code a set number of times - like a race car doing laps. Learn the three-part loop header, count up, down, and by steps, and dodge the classic off-by-one bug.

javascript ~20 min Beginner friendly
The Big Idea

What is a for loop?

Loops are one of the fundamental constructs that let us control the flow of a program. A for loop repeats a block of code a specific number of times - so instead of writing console.log("hip hip hooray!") a hundred times, you write it once and tell JavaScript to repeat it.

A for loop in JavaScript follows this structure:

main.js
for (let i = 0; i < COUNT; i++) {
    // code to execute COUNT number of times
}

The first line is called the loop header, and it has three parts separated by semicolons. Each part has one job:

  • let i = 0 - the start: runs once, before anything else, and creates the loop variable i with its first value.
  • i < COUNT - the keep-going condition: checked before every lap. If it is true, the body runs. The moment it is false, the loop ends.
  • i++ - the update: runs at the end of each lap and changes i. i++ is shorthand for "add 1 to i".

The code between the curly braces { } is the loop body - that is what gets repeated. You can put as many lines as you want inside it, and you can use i in that code.

Heads up: for loops typically start counting at 0, not 1. And while the variable is usually named i, you can use any name you want - lap, count, whatever makes your code clear.

Old code alert: in older JavaScript you will often see var i = 0 instead of let i = 0. Both work, but let is the modern way and keeps i neatly contained inside the loop - so we use let in this tutorial.

Interactive

The loop header lab

Time to dissect a loop header. Edit the three numbers below and watch exactly which values i takes. Then press Watch it run to see the loop's four phases fire in order: start, check, body, update, check again...

Loop header dissector
for (let i = ; i < ; i += )
1. start: i's first value 2. keep going while: i < end 3. update: after each lap

loop body runs

Try this: set the start to 10, the end to 0, and the step to -1 to count down. Then try a step of 0 and see why the loop would never end!


See It Run

Your first loop

Here is the classic first for loop. Before you press Run, predict: what numbers will it print, and how many lines will there be?

main.js
// Explore this loop by changing the start value
// of i and the condition (i < 3)
for (let i = 0; i < 3; i++) {
    console.log(i);
}
Console
0
1
2

Three lines - but no 3! Walk it through: i starts at 0, and the check 0 < 3 is true, so the body prints 0. The update makes i equal 1, then 2 - both pass the check and get printed. But when i becomes 3, the check 3 < 3 is false, so the loop exits without printing.

  • The loop starts at 0, not 1.
  • The update runs at the end of each lap.
  • Once the condition is false, we exit the loop.
Level Up

Counting up, down, and by steps

The basic loop starts at zero, ends at some number, and counts up by 1. But the for loop is way more flexible than that. You can start and stop at any number and change i by any amount - even count down. You can use regular math in the update, like i = i + 2 or its shortcut i += 2.

Try to predict what each of these four loops prints before running. For each one, ask yourself:

  • What is the starting value of i?
  • What is the last value of i that passes the check?
  • How does each lap change i?
variations.js
console.log("Loops 0 to less than 10, counting by 2s:");
for (let i = 0; i < 10; i = i + 2) {
    console.log(i);
}

console.log("Loops 0 to and including 10, counting by 2s:");
for (let i = 0; i <= 10; i += 2) {
    console.log(i);
}

console.log("Counts down from 10 to 0 by 1s:");
for (let i = 10; i >= 0; i--) {
    console.log(i);
}

console.log("Prints the powers of 2 up to 128:");
for (let i = 2; i <= 128; i = i * 2) {
    console.log(i);
}
Console
Loops 0 to less than 10, counting by 2s:
0
2
4
6
8
Loops 0 to and including 10, counting by 2s:
0
2
4
6
8
10
Counts down from 10 to 0 by 1s:
10
9
8
7
6
5
4
3
2
1
0
Prints the powers of 2 up to 128:
2
4
8
16
32
64
128

Spot the difference: the first loop uses < 10 and stops at 8. The second uses <= 10 and includes 10. That one character decides whether the end number makes it in! Also notice the countdown: to count down you need both a condition like i >= 0 and a downward update like i-- (shorthand for "subtract 1").

Your Turn

Practice: count by 5s

1

Count by 5s

Write a program that uses a for loop to count by 5s up to 100. When run, your output should look like this:

Expected output
5
10
15
20
25
30
...
100
solution.js
// Start at 5, keep going while i <= 100, add 5 each lap
for (let i = 5; i <= 100; i += 5) {
    console.log(i);
}

Why <= 100 and not < 100? Because we want 100 itself to print. With <, the loop would stop at 95 - a classic off-by-one bug (more on those below).


More Power

Making loops do real work

As you can see, for loops make life as a programmer much easier by repeating code a specific number of times. So what can we do besides printing lines of numbers?

One big use is looping over a set of numbers to compute a single value, like a sum or a product. This program adds up every number from MIN to MAX. Each lap, it adds the current value of i onto a running total stored in sum:

sum.js
// Explore this program by changing MIN and MAX
let MIN = 0;
let MAX = 100;
let sum = 0;

for (let i = MIN; i <= MAX; i++) {
    sum = sum + i;
}

console.log("The sum of the numbers is " + sum);
Console
The sum of the numbers is 5050

Notice that sum is created before the loop starts. If it were created inside the body, it would reset to 0 on every lap and the total would never grow.

Your Turn

Practice: 10!

2

The factorial of 10

Write a program that finds the product of the numbers from 1 to 10 - also known as the factorial of 10, written 10!. You will need a variable to store the growing product.

Hint: think carefully about your starting value!

solution.js
// product starts at 1, NOT 0
let product = 1;

for (let i = 1; i <= 10; i++) {
    product = product * i;
}

console.log("10! is " + product);
Console
10! is 3628800

Did you catch the hint? If product started at 0, then every multiplication would give 0, because anything times 0 is 0. For products, start at 1. For sums, start at 0.


Bug Patrol

Off-by-one gotchas

The most common loop bug in the world is being off by exactly one lap. It almost always comes from one of these two mixups:

  • Mixing up < and <=. The loop for (let i = 1; i < 10; i++) stops at 9 - it never runs with 10. If you wanted 10 included, you needed i <= 10.
  • Forgetting the loop starts at 0. The loop for (let i = 0; i < 5; i++) runs 5 times, but the values of i are 0, 1, 2, 3, 4 - not 1 through 5.

Here is a handy rule of thumb: starting at 0 with i < N runs the body exactly N times. Count the laps for yourself:

offbyone.js
// Both loops run 5 times, but print different numbers!
console.log("Loop A:");
for (let i = 0; i < 5; i++) {
    console.log(i);
}

console.log("Loop B:");
for (let i = 1; i <= 5; i++) {
    console.log(i);
}
Console
Loop A:
0
1
2
3
4
Loop B:
1
2
3
4
5

Debugging tip: when a loop prints one number too many or too few, do not stare at the body - check the header. Ask: what is the first value of i? What is the last value that passes the condition? The loop header lab above is great for checking your answer.


Beyond the Basics

Loops and graphics

You have now mastered the basics of for loops - congratulations! But do not stop here. Keep going to discover nested loops and how to loop over data structures like arrays and strings.

You can also use for loops to draw! This program uses the CodeHS graphics library - so instead of console.log, it uses special drawing commands like Circle and add() that only work in the CodeHS JavaScript graphics editor. The loop draws 7 circles, each one 10 pixels smaller than the last, in random colors - a rainbow! Try changing the loop to create more layers:

rainbow.js
// Sets the radius of the rainbow
let radius = 100;

// Uses a for loop to create each layer of the rainbow
for (let i = 0; i < 7; i++) {
    let arc = new Circle(radius);
    arc.setPosition(getWidth() / 2, getHeight() / 2);
    arc.setColor(Randomizer.nextColor());
    add(arc);
    radius = radius - 10;
}

// Adds a circle in the center to create the
// appearance of the arc
let center = new Circle(30);
center.setPosition(getWidth() / 2, getHeight() / 2);
center.setColor(Color.white);
add(center);

// Adds a white rectangle to create a horizon
let horizon = new Rectangle(getWidth(), getHeight() / 2);
horizon.setPosition(0, getHeight() / 2);
horizon.setColor(Color.white);
add(horizon);
Canvas (one possible result - the colors are random!)
// 7 laps, 7 arcs:

Look closely: the loop body does two jobs each lap - it draws a circle and shrinks radius by 10. Because each new circle is drawn on top of the bigger ones, only a ring of each color stays visible. To add more layers, change i < 7 to a bigger number.


Code

A JavaScript loop example

JavaScript for loops repeat code a set number of times. This program counts and prints an array.


Check Yourself

Quick quiz

1. What does this loop print?

for (let i = 0; i < 3; i++) {
    console.log(i);
}

2. In the header for (let i = 0; i < 10; i += 2), when does i += 2 run?

3. Which loop prints exactly the numbers 10, 20, 30, 40?

Keep learning JavaScript

For loops repeat code a set number of times. Next, learn while loops, which repeat as long as a condition is true, or put your loops to work on arrays full of data.