How to Get an Index in a for…of Loop in JavaScript and Node.js

JavaScript introduced the for…of loops with ECMAScript 2015. The for loop provides a convenient way of iterating over a collection of items.

A downside of a for…of loop: by default, it doesn’t give you the item’s index. Yet, you can conveniently work around this shortcoming and this tutorial shows you how!

Node.js Series Overview

How to Get the Index in a for…of Iteration

Use JavaScript’s Array#entries method to create an array iterator. This iterator returns a key-value-pair for each index-value combination in the array.

You can then destructure the index-value-pair using the array notation:

for (const [index, value] of ['Future', 'Studio'].entries()) {  
  console.log(index, value)
}

// 0 'Future'
// 1 'Studio'

Enjoy!

Explore the Library

Find interesting tutorials and solutions for your problems.