Arrays and Iteration
For-Of Iteration
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
factorstarts as2.numsis[1, 2, 3].- The loop visits each number once.
- Each pass adds
number * factortototal. - The script prints
factor=2andtotal=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.