AI Hints
JavaScript · Lesson 25 of 138

for Loops

Repeat with a counter.

⏱ 2 min read▶ Video at 30:03🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Computers are brilliant at repeating things, without getting bored. Print a hundred names, check a thousand prices, or count down from ten. Loops do the repeating. The most common one is the for loop.

for Loops
From the video: for Loops
  • Computers love repeating
  • A hundred names, a thousand prices
  • The for loop

Three parts

A for loop has three parts, separated by semicolons. Start the counter at one. Keep going while it's five or less. And add one after each round. Run it. The loop body ran five times, once for each value of I.

app.jsjavascript
for (let i = 1; i <= 5; i++) {
  console.log("Round", i);
}

console.log("Done!");
Output
Round 1
Round 2
Round 3
Round 4
Round 5
Done!

Counting down and adding up

The counter can count in any direction, and by any step. Here we count down from ten, by twos. Then we use a loop to add up all the numbers from one to a hundred. Run it.

app.jsjavascript
for (let i = 10; i > 0; i -= 2) {
  console.log(i);
}

let total = 0;
for (let n = 1; n <= 100; n++) {
  total += n;
}
console.log("Sum of 1 to 100:", total);
Output
10
8
6
4
2
Sum of 1 to 100: 5050

Summary

A for loop has a start, a condition, and a step. It repeats its body while the condition is true. Next, while loops.

Key takeaways
  • for (start; condition; step)
  • i++ or i -= 2
  • Running totals
Next up: while Loops — repeat until