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) {
  console.log(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}`);
});

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!