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.
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.
Each pass of a for loop with let gets a fresh binding of the counter, which is why closures created inside the loop capture the value of that pass. With var all closures share one variable.
The three clauses are all optional: for (;;) is an infinite loop. Keep the counter's update in the header rather than the body so the loop's shape is visible at a glance.
For reading every element, for...of (for (const item of items)) is clearer and avoids index errors. Use an index loop when you need the position, a custom step, or to walk backwards.
Cache nothing manually for performance: modern engines optimise i < arr.length. Readability and correct boundaries matter far more than micro-optimisation.
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.
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.
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
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.
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 explanationfor 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 predictionLoop 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.
DebuggingUndefined 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 generationLoop 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 reviewRepeated 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.