The for…of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.
for (variable of iterable) {
statement
}Example:
const iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30But some time we want to access index of each element. For this purpose we can use counter.
let counter = 0
const iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value, counter);
counter += 1;
}
// 10, 0
// 20, 1
// 30, 2There is another way to get index using entries() on array.
const iterable = [10, 20, 30];
for (const [index, value] of iterable.entries()) {
console.log(value, index);
}
// 10, 0
// 20, 1
// 30, 2
