Learn JavaScript
❯ control_flow.for_loop

for Loop in JavaScript

$concept

The classic for loop packs initialization, condition, and step into one header: for (let i = 0; i < n; i++). It is the precision tool for counted repetition — indexed traversal, fixed iterations, stepped sequences — with everything controlling the loop in one line.

Declaring the counter with let scopes it to the loop (each iteration gets a fresh binding — closures inside capture correctly, unlike legacy var). Any header slot may empty out, but an empty condition means infinite.

$how it works
1

Three slots, one line

Init runs once, condition tests before every pass, step runs after each body.

2

let scopes the counter

for (let i ...) confines i per-iteration — closures created inside capture the right value automatically.

3

Stepping and bounds

i += 2 strides, i-- counts down; i < arr.length matches zero-based indexing.

4

Empty slots are legal

for (;;) loops forever — pair with break, or fill all slots for clarity.

$example
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
console.log(sum);
Output
15
1i runs 1 through 5 — five iterations.
2Each pass adds the current i: 1+2+3+4+5 accumulates.
315 prints once the condition fails past 5.
$complexity
time O(n)
space O(1)

One pass over n iterations with constant extra state.

$use cases
Indexed array traversal when the index itself matters
Stepped sequences and countdowns via custom init/step
Fixed-iteration simulations and numeric methods
Nested loops for grids and pairwise comparisons

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.