In this post we cover how to get the index in a forEach loop in JavaScript
How to get the index in a forEach loop in JavaScript
To get the index of the current iteration within a Array.prototype.forEach loop, it can be taken from the callbacks arguments.
The first argument provided into the callback will be the item itself, the second argument will be the current index of the iteration and the third argument passed in will be the full array that is being looped over.
1const arrayA = ['a', 'b', 'c'];
2
3const callback = (arrayItem, index, arr) => {
4 console.log(item, index, arr);
5};
6
7arrayA.forEach(callback);
Array.prototype.forEach
Array.prototype.forEach or Array.forEach is a method on a Javascript array that will allow you to use a callback function to loop over each item in the array.
It is essentially syntactic sugar for a for loop with a given array, although it is not an exact replacement for a for loop because of things like async code.
The callback will be called for each iteration of the loop with each item passed in as an argument of the callback.
JavaScript
JavaScript is a programming language that is primarily used to help build frontend applications.
It has many uses, such as making network requests, making dynamic or interactive pages, creating business logic and more.
Loop
A loop in software engineering is reoccurring code that runs a number of times based on what it has been provided.
There are a number of ways to run loops, however for the most part there will be a iterator variable that will be incremented in value for each iteration of the loop. The iterator is usually set to the number 0, to start and after each iteration or run of the loop the variable will be incremented or increased by 1.
In order to prevent an infinite loop which is where the code gets stuck endlessly running the loop over and over again there is often a condition set that when met will end or break out of the loop.
For example if the loop increments by 1 for each iteration, then the condition set could be that while the iterator is less than the value of 10, run the loop otherwise break it.
A common condition is to find the total length of an array and use that to determine when each item has been looped over.
Further resources
Related topics
Save code?