How to get the current Element’s Index in JavaScript for…of Loop?

Navigating arrays in JavaScript is a common task, but what if you need not just the element but also its index in a for...of loop? In this blog post, we’ll uncover a neat JavaScript trick to easily retrieve the current element’s index while iterating through an array using the for...of loop. Let’s dive in and make our array-handling skills even more powerful!

Unveiling the Magic of Index Retrieval

The Basics

In a traditional for loop, getting the index is straightforward, but with the more modern for...of loop, it’s not immediately obvious. Fear not! Here’s a simple JavaScript snippet to make this task a breeze:

Breaking it Down

  • myArray.entries(): This method returns an iterator object with key-value pairs of array elements, where the key is the index and the value is the element.
  • for (const [index, element] of myArray.entries()): This destructures the key-value pairs obtained from entries(), assigning the index to the variable index and the element to the variable element.

Putting it Into Action

Now, let’s apply this knowledge to a real-world scenario. Imagine you want to find and log the index of a specific element in an array:


Let’s explore additional examples to showcase the versatility of this approach. Suppose you want to filter out elements with odd indices:

Or, you might want to double the value of each element at even indices:


And there you have it! With this elegant for...of loop trick, you can effortlessly access both the element and its index, enhancing your array iteration capabilities in JavaScript.

So, the next time you find yourself looping through an array, remember this handy technique. Happy coding!

Navigating arrays is like exploring a treasure trove of data. Here’s to finding your coding gems!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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