How to loop through an array with an index
Short answer
In forEach() the function receives the index as its second argument:
['a', 'b', 'c'].forEach((value, index) => {
console.log(index + ': ' + value);
});Output:
0: a
1: b
2: cThe for...of loop
In for...of the entries() method provides the index. This loop can be stopped with break:
for (const [index, value] of ['a', 'b', 'c'].entries()) {
console.log(index + ': ' + value);
}Output:
0: a
1: b
2: cNumbering from one
Indexes start at zero. Add one for human-friendly numbering:
['tea', 'milk'].forEach((item, index) => {
console.log(index + 1 + '. ' + item);
});Output:
1. tea
2. milkCommon mistake
forEach() cannot be stopped with break, and return inside it only skips the current element. If you need to stop the loop, use for...of:
[1, 2, 3, 4].forEach((n) => {
if (n > 2) return;
console.log('forEach', n);
});
for (const n of [1, 2, 3, 4]) {
if (n > 2) break;
console.log('for...of', n);
}Output:
forEach 1
forEach 2
for...of 1
for...of 2Functions used in this recipe
- Array.prototype.forEach — Runs a function for every element of an array.
- Array.prototype.entries — Returns index–element pairs for a for...of loop.