This post will discuss how to loop through an array with index in JavaScript.

1. Using a loop

We can use a for…of loop to iterates over the values of an array. The for…of loop does not provide the index directly, but we can use the Array.entries() function to get an iterator of [index, element] pairs from the array, and then use destructuring assignment to unpack key-value pairs inside the loop.

Download  Run Code

 
Alternatively, we can use a traditional for loop that uses a variable to keep track of the index. This is the most basic and widely supported way to loop over an array with an index. We can access the array element by using the bracket notation with the index variable.

Download  Run Code

2. Using Array.forEach() function

Another option is to use the Array.forEach() function that takes a callback function as an argument. The callback function receives three parameters: the current element, the current index, and the array itself. We can use the second parameter to access the index inside the callback function. This has a benefit over the traditional for-loop as there is no need to explicitly maintain the indexing information.

Download  Run Code

3. Using jQuery library

We can also use the third-party libraries to loop over an array with an index in JavaScript. We can use the $.each() function from the jQuery library, which takes an array and a callback function as arguments, and executes the callback function for each element in the array. The callback function receives two parameters: the index and the value. We can use the first parameter to access the index inside the callback function.

Download Code

4. Using Lodash library

Similarly, we can use the _.each function (alias _.forEach) from the Lodash or Underscore library. The _.each() function takes an array and a callback function as arguments, and invokes the callback function for each element in the array. The callback function receives three parameters: the value, the index, and the array itself. We can use the second parameter to access the index inside the callback function.

Download Code

That’s all about looping through an array with index in JavaScript.