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.