The for loop
- Node.js course
- Beginner
- Lesson 42/116
- 4 min
Learn to write counted loops with for.
The for loop
For tasks that repeat a fixed number of times you use the for loop. The form is for (init; condition; step) { ... }. Init runs once, the condition is tested each iteration, the step is applied after each iteration.
For example for (let i = 1; i <= 5; i++) { console.log(i); } prints numbers from 1 to 5. i++ increases i by one each step. The loop ends when the condition becomes false. Starting the counter at 1 suits a 1-5 range; for arrays you should start at 0.
Counter and step
In a for loop the counter is usually a variable named i. It takes a starting value, the condition checks an upper bound, and the step increases or decreases it. i++ adds one, i-- subtracts one, i += 2 adds two.
Although the counter is traditionally i, nested loops often use j and k. The starting value and step determine how many times the loop runs. For example for (let i = 0; i < 10; i += 2) produces 0, 2, 4, 6, 8.
Practice Print from 1 to 5
Write a for loop: counter i starts at 1, condition is i <= 5, step is i++. The body calls console.log(i). The output must be five lines: 1, 2, 3, 4, 5.
Starter code
// Write the for loop hereSample solution
for (let i = 1; i <= 5; i++) {
console.log(i);
}Expected output
1 2 3 4 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the output of for (let i = 1; i <= 3; i++) { console.log(i); }?
for (let i = 1; i <= 3; i++) { console.log(i); }- 0 1 2
- 1 2 3 Correct answer
- 1 2 3 4
- 3 2 1
Explanation: i starts at 1, includes 3; each step adds 1.
2 Write the for header
____ (let i = 0; i < 5; i++) {
console.log(i);
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
Explanation: for builds a counted loop.
3 Match each part to its job
| Term | Meaning |
|---|---|
let i = 0 |
Init |
i < 5 |
Condition |
i++ |
Step |
{ ... } |
Loop body |