Javascript: Get loop counter/ index in loop

While working in javascript arrays, we often encounter a situation where we need to get the loop index of loops like for..of loop or for each loop. This article will see different ways to get the counter or index of a loop in javascript.

Table of Contents:

Get loop counter or loop index: for of loop

Example:-

Get loop index of each element of array [78,89,54,3,901,1177]

Code:-

let myArray = [78,89,54,3,901,1177]
 function getIndex(_array)
 {
   for (const [i, value] of _array.entries())
     {
 // _array.entries() gets the array iterator object containing key-value pairs for each index in the array.
 //%d represents numeric and %s represents string value
      console.log('%d: %s', i, value);
      }
 }
// usage of the function
 getIndex(myArray)

Output:-

0: 78
1: 89
2: 54
3: 3
4: 901
5: 1177

Explanation:-

  • In the above code, a for of loop is run on _array.entries() which returns the array iterator object containing key-value pairs for each index in the array.
  • Within the loop index: value is printed on the console. Here, d% represents a digit and s% represents a string.

Get loop counter or loop index: for each loop

Example:-

Get loop index of each element of array [78,89,54,3,901,1177]

Code:-

let myArray = [78,89,54,3,901,1177]
function getIndex(_array)
{
// within for each anonymous function is used to get the index and value for every element of the array
  _array.forEach(function (value, i) 
  {
//%d represents numeric and %s represents string value
    console.log('%d: %s', i, value);
  });
}
// usage of the function
 getIndex(myArray)

Output:-

0: 78
1: 89
2: 54
3: 3
4: 901
5: 1177

Explanation:-

  • In the above code, a for each loop is run.
  • An anonymous function is used within the loop to get the index and the array value printed on the console.
  • Here, d% represents a digit and s% represents a string.

Get loop counter or loop index: for each loop

Example:-

Get loop index of each element of array [78,89,54,3,901,1177]

Code:-

let myArray = [78,89,54,3,901,1177]
function getIndex(_array)
{
  for (var e in _array)
   {
    console.log(e +":" +   _array[e]);
   }
}
// usage of the function
 getIndex(myArray)

Output:-

0: 78
1: 89
2: 54
3: 3
4: 901
5: 1177

Explanation:-

  • In the above code, a for in loop is run.
  • Since the loop is iterated on variable e. Index is the variable e and _array[e] is the value at the corresponding index-e.

Read More:

I hope this article helped you to get the loop counter in javascript loops. Good Luck !!!

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top