JavaScript for Loops: Counted Iteration
Quick answer
A counted for loop repeats a body while a condition remains truthy. Its header groups the initial state, continuation test and update expression.
How it works
In for (let i = 0; i < n; i++) { ... }, initialization runs once, the test precedes each body execution and the update follows each completed iteration (also after a continue targeting this loop). For nonnegative integer n, the counter visits 0 through n-1. A false initial test skips the body. All three header expressions can be omitted, but termination then needs explicit reasoning.
Expected output in Node.js:
012The counter stops before reaching 3.
let total = 0;for (let i = 1; i <= 4; i++) { total += i; }console.log(total);Expected output in Node.js:
10The inclusive range adds 1, 2, 3 and 4.
Common mistakes
An off-by-one error often comes from using <= when the intended index range ends before n. Keep the counter change consistent with the stopping condition.
Practice
Sum integers from 1 through n, returning zero when n is zero.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript for Loops: Counted Iteration — Knowledge Check
Apply the taught concept and reason about the result.
How often does initialization run in an ordinary counted for loop?
How many times does for(let i=0;i<4;i++) execute its body?
What does a false initial for-loop test cause?
What is the sum of 1 through 4 inclusive?
What does continue targeting a counted for loop do before the next test?