Tip: Get the index of an array item in a JavaScript for...of loop

JavaScript, Array, Iterator · Jul 25, 2021

JavaScript's for...of loops provide an easy way to iterate over all kinds of iterables from arrays and stings to Map and Set objects. One supposed limitation over other options (e.g. Array.prototype.forEach()) is that you only get the value of each item in the iterable. But that is not necessarily the case, as you can easily leverage Array.prototype.entries() to get both the index and value of each array item:

const items = ['a', 'b', 'c'];

for (let [index, item] of items.entries()) {
  console.log(`${index}: ${item}`);
}
// LOGS: 0: a, 1: b, 2: c

Moreover, you can use the spread operator (...) to convert a string into an array and then use Array.prototype.entries() the same way. Finally, both Map and Set prototypes provide a similar method (Map.prototype.entries() and Set.prototype.entries() respectively), which can be used the exact same way.

If you're not familiar with for...of and its syntax, I highly recommending you take a look at this article about the various iteration methods in JavaScript.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Array Methods

    Get acquainted with some common JavaScript array methods, as well as some more advanced array tricks.

    Collection · 7 snippets

  • Tip: Refactoring your for...in loops to avoid ESLint warnings

    ESLint is a very powerful tool that can save you a lot of headaches, but sometimes it gets in the way. Learn how to refactor code to get rid of a common warning.

    JavaScript, Array · Jun 12, 2021

  • Stable sort

    Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.

    JavaScript, Array · Oct 22, 2020

  • N random elements in array

    Gets n random elements at unique keys from an array up to the size of the array.

    JavaScript, Array · Oct 22, 2020