This post will discuss how to find the current index in a forEach and for…of loop in JavaScript.

Finding the current index in a forEach and for…of loop in JavaScript is a common task that can be done in different ways. A loop is a way of iterating over an array or an iterable object, and executing a function for each element. However, the function does not have direct access to the index of the element, unless it is provided as an argument. Here are some of the ways to find the current index in a loop in JavaScript:

1. Using callback function

The most straightforward way to get the current index in a foreach loop is to use the second argument of the callback function that is passed to the Array.forEach() function. This parameter will hold the index of the element being processed in the array, and can be used inside the function body. For example, this code will log the index and the value of each element in the array:

Download  Run Code

Output:

0: apple
1: banana
2: orange

2. Using a separate variable

Another way is to use a separate variable that is initialized outside the loop and increment it inside the loop. This variable can act as a counter that keeps track of the index of the current element. Here’s an example of how we can achieve this:

Download  Run Code

 
This will output the same as the previous function. However, this function is less elegant and may introduce errors if the variable is modified elsewhere.

3. Using Array.entries() function

A more modern way to get the current index in a for loop is to use the Object.entries() function and the for…of statement. The Array.entries() function returns an iterator object that contains the index and value of each array element. We can use a for…of loop to iterate over this array and use destructuring to assign the key and value to variables. For example, using the same array as before, we can do this:

Download  Run Code

Output:

0: apple
1: banana
2: orange

 
This will also output the same as the previous functions. This function is simple and concise, but it may not be supported by older browsers.

These are some of the ways to find the current index in a forEach and for…of loop in JavaScript. We can also modify them according to our needs or preferences.