/

How to Get the Index of an Iteration in a for-of Loop in JavaScript

How to Get the Index of an Iteration in a for-of Loop in JavaScript

In JavaScript, a for-of loop is a powerful feature introduced in ES6 that allows you to iterate over an array effortlessly. However, by default, it does not provide a straightforward way to access the index of each iteration. But worry not! In this blog post, I will show you how to easily obtain the index of an iteration using a combination of the destructuring syntax and the entries() method.

Let’s dive in!

The first step is to understand the basic structure of a for-of loop. Here’s an example:

1
2
3
for (const value of ['a', 'b', 'c']) {
console.log(value)
}

In this code snippet, we are iterating over an array ['a', 'b', 'c'] using a for-of loop. The loop variable value will hold the value of each element during each iteration.

Now, let’s see how we can obtain the index of each iteration. JavaScript provides the entries() method for arrays, which returns an iterable object with key-value pairs. By using destructuring assignment, we can easily extract the index and value for each iteration.

Here’s the modified for-of loop code:

1
2
3
for (const [index, value] of ['a', 'b', 'c'].entries()) {
console.log(index, value)
}

In this code snippet, we call the entries() method on the array ['a', 'b', 'c']. The method returns an Iterable iterator that gives us an array-like object with key-value pairs. We then use destructuring assignment to assign the index to the variable index and the value to the variable value during each iteration.

Finally, we can log the index and value to the console to see the result.

That’s it! By combining the destructuring syntax with the entries() method, we can easily obtain the index of each iteration in a for-of loop.

I hope this blog post helps you in understanding how to get the index of an iteration in a for-of loop in JavaScript. Feel free to explore more about JavaScript ES6 and its features.

tags: [“JavaScript”, “for-of loop”, “ES6”, “array”, “iteration”, “index”]