JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 4: Repetition and Problem-SolvingLesson 16 of 150About 45 minutes

Lesson 16: For loops

01Opening question

A receipt prints one line for each of 40 items. Would you write console.log 40 times?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Change 3 to 5 and run again. The loop body is written once and runs as many times as the condition allows.

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

03Objective and prerequisites

Learning objective: Write for loops with a start, condition and update, count up and down, step by more than one, and loop over the indexes of a string or array.

You need: Lesson 13: If, else if and else, Lesson 15: Building decision-making applications

Skills practised: Loops, for loops.

04Explanation

A loop repeats a block of code. A for loop has three parts inside its brackets, separated by semicolons: a start (let i = 1), a condition (i <= 3) and an update (i++).

Before every pass JavaScript checks the condition. If it is true the body runs, then the update runs. When the condition becomes false the loop ends and the program continues after the closing brace.

i is the loop counter. It is a normal variable, so the body can use it: print it, multiply it, or use it as an index such as items[i].

Arrays and strings start at index 0, so a loop over them usually reads for (let i = 0; i < items.length; i++). Use <, not <=, or you will read one position past the end.

05Definitions

Loop
Code that repeats a block while a condition stays true.
Iteration
One pass through the body of a loop.
Loop counter
The variable, often i, that changes each iteration and controls when the loop stops.
Increment (i++)
Adds one to a variable.
for...of
A loop that gives each element of an array or string in turn.

Open the full glossary

06Visual learning object

For-loop explorer. Set the start, condition and step, then watch each check of the condition and each value of the counter.

Loading the interactive object…

Open the full For-loop execution explorer page with its guided experiment.

07Examples

ex-016-01Counting up Browser-executable JavaScript

The counter starts at 1 and increases until the condition is false.

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
Sample input
None
Expected output
1 2 3 4 5
Common mistake
Writing commas instead of semicolons between the three parts.
Try this
Print the numbers 1 to 10.
Source
examples/ex-016-01-count-up.js (repository pending publication)

ex-016-02Counting down and stepping Browser-executable JavaScript

The update can subtract, or add more than one.

for (let i = 3; i >= 1; i--) {
  console.log("T-minus", i);
}
for (let n = 0; n <= 20; n += 5) {
  console.log(n);
}
Sample input
None
Expected output
T-minus 3 T-minus 2 T-minus 1 0 5 10 15 20
Common mistake
Counting down with i++, which never makes i >= 1 false.
Try this
Print the even numbers from 10 down to 0.
Source
examples/ex-016-02-count-down-step.js (repository pending publication)

ex-016-03Looping over an array by index Browser-executable JavaScript

Indexes run from 0 to length - 1.

const items = ["Pen", "Notebook", "Bag"];
for (let i = 0; i < items.length; i++) {
  console.log(`${i + 1}. ${items[i]}`);
}
Sample input
None
Expected output
1. Pen 2. Notebook 3. Bag
Common mistake
Using i <= items.length, which reads items[3] as undefined.
Try this
Add a fourth item and check that the loop still works without changes.
Source
examples/ex-016-03-loop-array.js (repository pending publication)

ex-016-04for...of for each value Browser-executable JavaScript

When you need values rather than positions, for...of is shorter.

const prices = [4.5, 12, 3.25];
let total = 0;
for (const price of prices) {
  total += price;
}
console.log("Total:", total);
for (const letter of "JS") {
  console.log(letter);
}
Sample input
None
Expected output
Total: 19.75 J S
Common mistake
Using for...in on arrays, which gives index strings, not values.
Try this
Count how many prices are above 4.
Source
examples/ex-016-04-for-of.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the receipt loop

Correct a loop boundary so every item prints exactly once.

const items = ["Apples", "Bread", "Milk"];
for (let i = 0; i <= items.length; i++) {
  console.log("-", items[i]);
}

Times table

Use the counter in a calculation.

const n = 7;
// TODO: print "7 x 1 = 7" up to "7 x 5 = 35" with a for loop

Order total

Accumulate a total with a loop.

const quantities = [2, 1, 3];
const unitPrices = [4, 10, 2.5];

09Prediction

Commit to an answer first, then run the real code to compare.

let out = "";
for (let i = 0; i < 4; i += 2) {
  out += i;
}
console.log(out);

What is printed?

10Debugging investigation

The receipt skips the first item

A three-item receipt only shows two items and the total is too low.

const prices = [2, 3, 4];
let total = 0;
for (let i = 1; i < prices.length; i++) {
  total += prices[i];
}
console.log(`Total: $${total}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Printing a receipt

A point-of-sale screen prints one line per cart item and a total. The number of items changes with every customer, so the code must loop over the array instead of printing fixed lines.

const cart = ["Tea", "Scone"];
for (let i = 0; i < cart.length; i++) {
  console.log(`${i + 1}. ${cart[i]}`);
}

12Knowledge check

1. How many lines are printed?

for (let i = 0; i < 3; i++) {
  console.log(i);
}
  • 2
  • 3
  • 4
  • 0

2. Which part of a for loop runs after every iteration?

  • The start
  • The condition
  • The update
  • None of them

3. Why does this print undefined at the end?

const a = ["x", "y"];
for (let i = 0; i <= a.length; i++) console.log(a[i]);
  • for loops cannot read arrays
  • <= reads one index past the end
  • i should start at 1
  • The array is empty

4. What is printed last?

for (let i = 0; i < 10; i += 2) console.log(i);
  • 10
  • 8
  • 6
  • 12

5. Which loop gives each value of an array directly?

  • for...in
  • for...of
  • do...while
  • if

6. To print five items, which is better?

  • Five console.log lines
  • One console.log inside a loop
  • They are identical in every way
  • Neither

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the receipt loop: Prints three items; Uses < length
  • Times table: Prints five lines; Uses a for loop
  • Order total: Prints the total; total is 25.5; Uses a loop
  • ex-016-01: output matches the documented expected output
  • ex-016-02: output matches the documented expected output
  • ex-016-03: output matches the documented expected output
  • ex-016-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-04-repetition-and-problem-solving/lesson-016-for-loops/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • A for loop has start; condition; update.
  • The condition is checked before every iteration.
  • Arrays run from index 0 to length - 1, so use <.
  • for...of gives each value when the index is not needed.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation for loops
Context: I am learning for loops.
Task: Explain start, condition and update with a step-by-step trace of a loop from 1 to 3.
Constraints: Beginner level.
Expected behaviour: I can trace a loop on paper.
Testing: Give me three loops to trace.
Code prediction Loop tracing drill
Context: I know the three parts of a for loop.
Task: Show me six short loops and ask how many times each runs and what it prints.
Constraints: Wait for my answers.
Expected behaviour: Include counting down and steps of 2 or 5.
Testing: Explain any I miss with a trace table.
Debugging Undefined at the end
Context: My loop prints undefined after the last item.
Task: Help me find the boundary mistake with questions.
Constraints: No direct answer at first.
Expected behaviour: I fix it myself.
Testing: Suggest a console.log that reveals the index.
Exercise generation Loop practice
Context: I finished the order total exercise.
Task: Create three loop exercises with shopping data.
Constraints: Fictional data, exact output.
Expected behaviour: One counts down, one steps by 5, one totals an array.
Testing: Include solutions in a hidden section.
Code review Repeated lines
Context: My program repeats console.log ten times with small changes.
Task: Show me how to replace them with a loop.
Constraints: Keep output identical.
Expected behaviour: Only one console.log remains.
Testing: Explain the counter values.