How can I iterate through an array with its index and value?
Quick answer
Use a for loop when you want to access each value through an index variable, or use forEach() with callback parameters (value, index). Both can print the same index-value pairs. In forEach(), the value comes first and the numeric index second; in a for loop, you use the index to read the value from the array. [S1]
The question, the details, the next step.
A practical checklist
Use
for (let index = 0; index < items.length; index++)when you want an explicit index variable.Use
items[index]in an index-based loop to read the value at that position.For
forEach(), write callback parameters in the order(value, index).Log both values together, such as
console.log(index, value), to check the pairs.If a
forEach()callback appears to skip a position, check whether that array index is a sparse hole.
A few more useful answers
Can I name the `forEach()` callback parameters `index` and `value`?
You can choose those names, but the first parameter still receives the value and the second receives the index. To avoid confusion, use names in the order (value, index).
Does returning a value from `forEach()` create a new array?
No. forEach() discards the callback’s return value and returns undefined; it is intended for iteration, not collecting transformed results. [S1]
Can I stop a `forEach()` loop with `break`?
No. The reference notes that forEach() cannot be exited early with break. [S1]
Sources
References used for this guide.
- [S1] Array.prototype.forEach() — JavaScript reference learn.microsoft.com · Checked
