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

The for-of loop introduced in ES6 is a good way to traverse an array:

for (const v of ['a', 'b', 'c']) {
  console.log(v)
}

How to get the iteration index?

Loop does not provide any syntax to do this, but you can use the introduced destructuring syntax in combinationES6callentries()Method on the array:

for (const [i, v] of ['a', 'b', 'c'].entries()) {
  console.log(i, v)
}

Download mine for freeJavaScript beginner's manual


More js tutorials: