Visit each element of an array with for-of.

For-Of Iteration

for_of.js
const factor = 2;
const nums = [1, 2, 3];
let total = 0;
for (const n of nums) {
  total += n * factor;
}

console.log("factor=" + factor);
console.log("total=" + total);

Follow the Loop

  1. factor starts as 2.
  2. nums is [1, 2, 3].
  3. The loop visits each number once.
  4. Each pass adds number * factor to total.
  5. The script prints factor=2 and total=12. | number | added | running total | | --- | --- | --- | | 1 | 2 | 2 | | 2 | 4 | 6 | | 3 | 6 | 12 |
for-of A `for...of` loop reads each element in turn without needing an index. Here it accumulates a running total.

Exercise: for_of.js

Reproduce factor=2 and total=12, then use the pinned factor variants 3 and 5 to predict totals 18 and 30.