for...of
iterates arrays, array-like objects, and generally any iterable (maps, sets, DOM collections). You can destructure the iterated item in place. On top of that, for...of
has a short syntax.
const fruits = ['oranges', 'apples'];
for (const fruit of fruits) {
console.log(fruit);
}
// 'oranges'
// 'apples'
Note that in
for-of
loops you can useconst
. Think of it as a new const declaration being executed each time in a fresh scope.
The array method entries()
can be used to access the index of the iterated item. The method returns at each iteration a pair of [index, item]
.
const arr = ['oranges', 'apples'];
for (const [index, elem] of arr.entries()) {
console.log(`${index} -> ${elem}`);
}
// 0 -> oranges
// 1 -> apples
At each iteration arr.entries()
returns a pair of index and value, which is destructured by const [index, elem]
expression.
Iterating over an array of objects
Example 1:
const person = {
name: 'John Smith',
job: 'agent'
};
for (const [prop, value] of Object.entries(person)) {
console.log(prop, value);
}
// 'name', 'John Smith'
// 'job', 'agent'
where Object.entries(person)
returns an array of key and value tuples.
Example 2:
const persons = [
{ name: 'John Smith' },
{ name: 'Jane Doe' }
];
for (const { name } of persons) {
console.log(name);
}
// 'John Smith'
// 'Jane Doe'
The cycle for (const { name } of persons)
iterates the objects of persons
array, but also destructures the person object in place { name }
.
Maps and Sets iteration
const names = new Map();
names.set(1, 'one');
names.set(2, 'two');
for (const [number, name] of names) {
console.log(number, name);
}
const colors = new Set(['white', 'blue', 'red', 'white']);
for (color of colors) {
console.log(color);
}
String characters iteration
const message = 'hello';
for (const character of message) {
console.log(character);
}
// 'h'
// 'e'
// 'l'
// 'l'
// 'o'