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:
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.
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...
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!
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?
// 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); }
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.
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?
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); }
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").
Practice: count by 5s
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:
5 10 15 20 25 30 ... 100
// 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).
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:
// 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);
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.
Practice: 10!
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!
// product starts at 1, NOT 0 let product = 1; for (let i = 1; i <= 10; i++) { product = product * i; } console.log("10! is " + product);
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.
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:
// 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); }
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.
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:
// 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);
// 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.
A JavaScript loop example
JavaScript for loops repeat code a set number of times. This program counts and prints an array.
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.