Loop with an index to scan an array.

Indexed Loop

indexed_loop.js
const nums = [3, 7, 2, 8, 5];
const start = 0;
let max = nums[start];
for (let i = start; i < nums.length; i++) {
  if (nums[i] > max) {
    max = nums[i];
  }
}

console.log("start=" + start);
console.log("max=" + max);

Follow the Scan

  1. nums starts as [3, 7, 2, 8, 5].
  2. The default start is 0, so max begins at 3.
  3. The loop checks each value from index 0 onward.
  4. max changes to 7, then to 8.
  5. The script prints start=0 and max=8. | index | value | max after check | | --- | --- | --- | | 0 | 3 | 3 | | 1 | 7 | 7 | | 2 | 2 | 7 | | 3 | 8 | 8 | | 4 | 5 | 8 |
indexed-loop A counter-based `for` loop exposes the index, which is handy when the position matters, such as scanning for the largest value.

Exercise: indexed_loop.js

Reproduce start=0 and max=8, then use the pinned start variants 1 and 2 to predict that max stays 8 while the start line changes.