CodeBlanks Logo Icon CodeBlanks

The for loop

Learn the for loop structure: counter, condition and increment steps.

The for loop

The for loop runs a block a fixed number of times. Its header has three parts: init, condition and increment.

for (let i = 1; i <= 3; i++) {
  console.log(i);
}

Here i is the counter. Each step tests the condition; if true, it runs the block and increments. When false, the loop ends.

Sum and count patterns

The for loop is commonly used for two tasks: accumulating a sum, or walking through a sequence.

Sum example:

let total = 0;
for (let i = 1; i <= 5; i++) {
  total = total + i;
}
console.log(total); // 15

Here total is the accumulator. Each step adds i to it. When the loop ends, total is 1+2+3+4+5 = 15.

Practice Print 1 to 5

Use a for loop to print the numbers 1 to 5 with console.log.

Starter code

script.js
// Print 1 to 5 with console.log

Sample solution

script.js
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Practice Sum of numbers 1 to 10

Use a for loop to compute the sum of numbers 1 to 10. Accumulate it in a total variable and finally print it with console.log(total).

Starter code

script.js
// Compute the sum here
let total = 0;

Sample solution

script.js
let total = 0;
for (let i = 1; i <= 10; i++) {
  total += i;
}
console.log(total);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many times does this loop run?

script.js
for (let i = 0; i < 3; i++) {
  console.log(i);
}
  • 2 times
  • Forever
  • 4 times
  • 3 times Correct answer

Explanation: i starts at 0 and runs while less than 3. It runs for 0, 1, 2 — three times.

2 Complete the loop that counts down from 5 to 1

Question
for (let i = 5; i >= ____; i--) { console.log(i); }
Answer
for (let i = 5; i >= 1; i--) { console.log(i); }

Explanation: With 1 the condition becomes i >= 1 and 5, 4, 3, 2, 1 are printed.

3 Match the for loop parts

Term Meaning
let i = 0 init
i < 5 condition
i++ increment
console.log(i) body

All lessons in Beginner