for...of
The for...of
statement is specifically designed to iterate over iterable objects, like strings and arrays, but does not work on object literals. Unlike the for
statement, the for...of
statement does not rely on an index to retrieve a value but instead stores each value to a defined variable.
With Arrays
The expression of the for...of
statement starts with an initialization of the variable used to hold each item's value. This is followed by the keyword of
and ends with the iterable.
const animals = ['cat', 'dog', 'mouse']
for (const animal of animals) {
// Logs all the animals in the array
console.log(animal)
}
const incomes = [62000, 67000, 75000]
let total = 0
for (const income of incomes) {
total += income
}
console.log(total) // 204000
With Strings
The for...of
statement also works with strings. When iterating over a string, the defined variable will be assigned to each character, one at a time.
const name = 'Master Bokuju'
for (const char of name) {
// Logs each character of the name
console.log(char)
}
This YouTube video was created by Steve Griffith.