Get The Current Array Index in JavaScript forEach()

Oct 9, 2020

JavaScript's forEach() function takes a callback as a parameter, and calls that callback for each element of the array:

// Prints "a, b, c"
['a', 'b', 'c'].forEach(function callback(v) {

The first parameter to the callback is the array value. The 2nd parameter is the array index. That's the current position in the array the forEach() loop is at.

// Prints "0: a, 1: b, 2: c"
['a', 'b', 'c'].forEach(function callback(value, index) {
  console.log(`${index}: ${value}`);

More Fundamentals Tutorials