If someone asked you to “count from 1 to 10 and show it,” would you write console.log(1); on ten lines? What if it were “1 to 10,000”? This kind of repeating the same thing is exactly what the computer is best at. The way to ask for it is the for statement.
Let’s write it
for (let i = 1; i <= 10; i = i + 1) {
console.log(i);
}In just three lines, the console shows 1 through 10 in order. Inside ( ) are three parts separated by ;, not commas.
| Part | Example | Meaning |
|---|---|---|
| Start | let i = 1 | Prepare a counting variable at 1 |
| Condition to keep going | i <= 10 | Keep going while i is 10 or less |
| How to advance | i = i + 1 | Increase i by 1 each lap |
Picture it going around and around: “set i to 1 → 10 or less? → run the thing to do → add 1 → 10 or less? → …”
It shines when combined with arrays
Where the for statement shines most is when you process an array’s contents in order.
const likes = ["drawing", "ramen", "games", "Shima"];
for (let i = 0; i < likes.length; i = i + 1) {
console.log(likes[i]);
}As i advances 0, 1, 2, 3, likes[i] is taken out in order, and all four favorites are shown. Because array numbers start at 0, the start is also let i = 0. The standard form for the condition is i < likes.length (while it’s less than the count).
Let’s see it in action
With a loop, let’s line up stars on the screen.
Summary of this lesson
for (start; condition to keep going; how to advance) { thing to do }lets you loop- Using the name
ifor the counting variable is the tradition - Use it together with an array and you can process every item in order