How to Get the Current Element's Index in a JavaScript forEach Loop?

In the JavaScript Array.prototype.forEach() method, you can get the index of the current element in the loop by using the (optional) second parameter of the callback function, for example, like so:

const arr = ['apple', 'banana', 'orange'];

arr.forEach((item, index) => {
  console.log(`${index}: ${item}`);
});

In this example, the callback function to Array.prototype.forEach() method has two parameters (i.e. the current element and its index). It produces the following output:

// '0: apple'
// '1: banana'
// '2: orange'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.