Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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: c

The 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: c

Numbering 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. milk

Common 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 2

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.