OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Loops and bounded repetition

Repeat work while keeping the accumulator and stopping rule visible.

Lesson 8 of 25 · About 20 minutes · Beginner · English

By the end of this lesson

Use for...of and a while loop that changes its own condition.

Before you start

  • Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
  • Complete lesson 7 or be comfortable with its examples.

Three words to know

Iteration
One pass through a loop.
Accumulator
A value updated as items are processed.
Termination
The point at which repetition stops.

1. Prefer values when you need values

for...of visits array values. for...in visits enumerable property keys and is usually the wrong choice for ordinary array items. Initialise an accumulator outside the loop so an empty input still has a defined result.

Sum page countsJAVASCRIPT · Node.js · save as lesson.mjs
const sizes = [2, 3, 1];
let total = 0;
for (const size of sizes) {
  total += size;
}
console.log(total);
What you should see · example output
6

2. Use positions explicitly

A conventional for loop can count positions. Here the upper bound is excluded. Avoid changing the same array’s size while iterating over it; that can skip or repeat unexpected work. Build another result when filtering.

Number a checklistJAVASCRIPT · Node.js · save as lesson.mjs
const steps = ["read", "test"];
for (let index = 0; index < steps.length; index += 1) {
  console.log(`${index + 1}. ${steps[index]}`);
}
What you should see · example output
1. read
2. test

3. A while loop must make progress

The loop body below changes remaining, the same value read by its condition. If a practice script loops forever, interrupt it with Ctrl+C and inspect the stopping rule. A byte limit on an input does not automatically impose a time limit on unrelated loops.

A short countdownJAVASCRIPT · Node.js · save as lesson.mjs
let remaining = 3;
while (remaining > 0) {
  console.log(remaining);
  remaining -= 1;
}
console.log("done");
What you should see · example output
3
2
1
done

YOUR TURN

A small check before you continue

Sum 1 through 5 with a loop. What initial value works when the list is empty?

Show a suggested answer

Start total at 0. Adding 1, 2, 3, 4 and 5 gives 15. An empty collection leaves total at 0 rather than undefined.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.