Arrays and Iteration
Indexed Loop
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
numsstarts as[3, 7, 2, 8, 5].- The default
startis0, somaxbegins at3. - The loop checks each value from index
0onward. maxchanges to7, then to8.- The script prints
start=0andmax=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.