Skip to content

Instantly share code, notes, and snippets.

@oliverjumpertz
Created December 24, 2020 20:45
Show Gist options
  • Save oliverjumpertz/2227e79d5b3c1eb6d8e5bd12be5e10a9 to your computer and use it in GitHub Desktop.
Save oliverjumpertz/2227e79d5b3c1eb6d8e5bd12be5e10a9 to your computer and use it in GitHub Desktop.
Iterating over values and indices with a for..of-loop
// Iterating over the array with each individual element at hand while separately
// keeping track of the index.
let i = 0;
for (const element of array) {
console.log(i++, element);
}
// Array.prototype.entries() returns an iterator that returns an array instead
// of each individual element each time next() is called.
// By using array destructuring, we take the tuple (array) the iterator returns on
// each iteration step and destructure it into individual variables.
// We can now iterate over the array while having the index and the element at hand on
// each iteration.
for (const [index, element] of array.entries()) {
console.log(index, element);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment