Exerpad
🔥 1
10 XP
Lesson · Chapter: For Loops+10 XP for reading

Looping with For

The for loop is a compact way to repeat things a specific number of times.

Where you'll use this
Drawing rows of pixels, sending an invitation to every friend, printing a report per player — when you know how many rounds, for is the tool.

The Three Parts

A for loop packs the counter setup, the condition, and the update into one line:

javascript
for (let i = 0; i < 5; i++) {
console.log("Hello!");
}
Output
Press Run to see the output.

This prints Hello! five times. The three parts, separated by semicolons:

  1. let i = 0 — start the counter at 0
  2. i < 5 — keep looping while this is true
  3. i++ — add 1 to the counter after each round

The variable i counts 0, 1, 2, 3, 4.

Counting from 1

Start and stop wherever you like:

javascript
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output
Press Run to see the output.

Output:

1
2
3
4
5

Counting by Steps

Change the update part to count by any amount:

javascript
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
Output
Press Run to see the output.

Output:

2
4
6
8
10

To count backwards, use i--:

javascript
for (let i = 3; i >= 1; i--) {
console.log(i);
}
Output
Press Run to see the output.

Looping Over Strings

Use for...of to visit each character in a string:

javascript
for (let letter of "Hello") {
console.log(letter);
}
Output
Press Run to see the output.

Output:

H
e
l
l
o

Looping Over Arrays

for...of works on arrays too (more on arrays soon!):

javascript
let colors = ["red", "blue", "green"];
for (let color of colors) {
console.log(color);
}
Output
Press Run to see the output.

For vs While

Use for when you know how many times to loop. Use while when you don't know in advance.

Did you know?
A modern processor can run a few billion loop laps per second. The loop you just wrote finishes faster than your screen can even show one frame.

Check yourself

Pause & predict — what will this print?
for (let i = 0; i < 3; i++) {
  console.log(i);
}