← Fundamentals
Fundamentals

For loops and iteration protocols

What does this loop give you, and when does it read it?

An iteration protocol determines which items a loop receives and how its updates reach storage.

Outcome

Distinguish indices, copied values and mutable elements, then preserve entry-state data during a simultaneous update.

Terminology (3)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Iteration value
The value or reference supplied for one execution of the loop body.
Writeback
Updating the original element storage, rather than only a local copy.
Entry state
The collection values when an operation begins, before any of its updates.

What an iteration supplies

A counted loop advances explicit control state; an iterable or range loop obtains successive items through its native iteration rules. Each item may be a position, a copied value or access to stored data. Identify that binding before reasoning about an assignment inside the body.

Also distinguish the current item from the collection state used by later iterations. An operation defined from one starting state needs a consistent source for all its reads. The loop spelling alone does not establish either writeback to the collection or a snapshot of its contents.

01Identify the values supplied by iteration

Identify the values supplied by iteration

A capacity-planning tool replays one worker-ring scheduler tick. It counts queued jobs, adds a fan-out batch to every worker, then models the configured half-backlog handoff to the next worker. Every handoff must use the counts after fan-out and before any handoff in the round, so one job cannot hop twice in that round.

This simulator replays the scheduler policy supplied for the test: half of each transfer-entry backlog moves one hop, rounded down. It makes no claim about optimal load balancing or real network migration. Incoming fan-out adds jobs; a handoff round preserves their total.

The first check is the queued-job total before the incoming batch is applied. Predict the sum, then identify whether the loop supplies a position, a value or a reference.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const counts = [2, 7];
let total = 0;

for (const value of counts) total += value;

console.log("total", total);
What prints?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts

Save one complete example at a time under the shown filename in a fresh folder. Run the shown command. The browser lab supplies its editor, input fixtures and runner.

02A local update may leave the collection unchanged

A local update may leave the collection unchanged

The total identifies how much work is waiting. The planner next adds the incoming fan-out batch to each queue. This reduced probe tries to add three jobs to each worker; predict the counts actually left in storage.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const counts = [2, 4];

for (let value of counts) {
  value += 3;
}

console.log("counts", counts[0], counts[1]);
Which stored counts print?

03A copied current value does not freeze future values

A copied current value does not freeze future values

Once the batch is accounted for, the handoff calculation must read one transfer-entry state. Before implementing that rule, test whether an ordinary pass already freezes later values: the first pass writes the second element. Predict what the next pass reads. This example changes existing storage only.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const counts = [2, 4];
const seen: number[] = [];

for (const [index, value] of counts.entries()) {
  seen.push(value);

  if (index === 0) counts[1] = 9;
}

console.log("seen", seen[0], seen[1]);
Which values were observed?

04Practice

Repair the worker-queue replay

Input is worker count, uniform bonus, then nonnegative worker counts. The complete parser, report helper, moveCount and receiver are supplied. Valid plans contain at most 100 workers, each queued count is 0 to 100, and the batch is 0 to 100. These supplied-input limits keep totals and intermediate counts within the native integer ranges; the parser does not enforce them. moveCount returns half rounded down; receiver selects the next worker with wraparound.

The final operation sends each worker’s outgoing amount simultaneously from its count at transfer entry. A one-worker ring sends to itself; an empty ring has no transfers. The printed total and full distribution are both observable.

Start the lab

Report queued work, apply each worker’s incoming batch, then compute simultaneous handoffs.

  1. easy · F-FOR-V4-1 Sum worker values
  2. medium · F-FOR-V4-2 Apply the worker bonus
  3. hard · F-FOR-V4-3 Transfer from one entry state
In the frontend Native writeback and a framework state update are different contracts. Optional

A native loop can update original integer elements through their storage. A React state update instead supplies a new array value; changing a local iteration number still updates neither storage nor state. This component maps each previous count to its replacement.

Svelte’s deep state proxy can observe array-element writes, but assigning to a local copied number still has no connection to that proxy. The example uses the same explicit array replacement to make the intended state change visible. These framework rules do not change the native range-variable rules above.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useState } from "react";

export function WorkerQueues() {
  const [counts, setCounts] = useState([2, 4]);

  function boost() {
    setCounts((previous) => previous.map((count) => count + 1));
  }

  return <button onClick={boost}>{counts.join(", ")}</button>;
}

The updater derives a new array from the previous state. Mutating a loop-local number would never call the state setter.

Sources: React: Updating arrays in state,Svelte: $state and deep state.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.