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.
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:
let i = 0— start the counter at 0i < 5— keep looping while this is truei++— 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.