| by Arround The Web | No comments

Get Loop Counter/Index Using for…of Syntax in JavaScript

The for…of loop in JavaScript is a new loop construct that was introduced in ECMAScript 6 (ES6) and is used to iterate over iterable objects, such as “arrays”, “strings”, and “maps”. It’s worth noting that the for…of loop does not provide direct access to the index/counter of the iteration. If you want to retrieve the index or counter, you can use the for…of loop in conjunction with the “Array.entries()” method.

This blog will define the way to get the loop counter using the “for…of” loop in JavaScript.

How to Get Loop Counter/Index Using for…of Syntax in JavaScript?

Use the “array.entries()” method to get the loop counter or indexes. It gives a new iterator object containing the array’s key/value pairs for each index.

Syntax

Follow the given syntax to get the loop counter using “for…of” loop:

for (const [i, e] of arr.entries()) {
 // .....
}

Here, “i” represents the “index” and “e” denotes the “elements” of an array:

Example

Create an array named “arr”:

const arr = ['alpha', 'beta', 'gamma'];

Iterate the array using the for…of loop:

for (const i of arr) {
 console.log(i);
}

It can be observed that console.log() method will just print the values of an array:

For getting the loop count or indexes, we will call the entries() method with an array in the for…of loop that will print the array elements with the loop count or the indexes of the elements in key/value pair:

for (const [i, e] of arr.entries()) {
 console.log(i, e);
}

The output indicates that the elements of an array are printed with the loop count or the indexes of elements:

You can also display the loop counter or the indexes with the elements using the literal notation (backticks) in the console.log() method:

We have compiled all the essential information related to getting the loop counter/index using the for…of loop in JavaScript.

Conclusion

To get the loop counter or the indexes of the loop, use the “array.entries()” method with the “for…of” loop. It gives a new iterator object containing the array’s key/value pairs for each index. This blog defined the method to get the loop counter using the “for…of” loop in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply