by Sai gowtham

How to get index in a for-of loop in JavaScript

In this tutorial, we are going to learn about how to get the index in a for-of loop.

Normally, if we loop through an array using for-of loop we only get the values instead of index.

const array = ['onion','noise','pin'];

for(const value of array){
    console.log(value);
}

To get the index in a for-of loop, we need to call the array with a entries() method and use destructuring syntax.

const array = ['onion','noise','pin'];

for(const [index,value] of array.entries()){
    console.log(index,value);
}

Note: The entires() method returns a new array with key-value pairs for each item in the array.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course