Introduction
This tutorial will learn about for-of
introduced in ES6
version of JavaScript.
The for...of
statement is used for iterating over arrays, maps or sets.
Looping over an array
Example in code:
const fruits = ['Orange', 'Apple', 'banana', 'Lemon']
// looping through
for (const fruit of fruits) {
// do something with fruit
console.log(fruit)
}
Looping over a string
for...of
can also be used to loop over contents of a string.
const words = 'Happy new year!'
for (const char of words) {
console.log(char) // H a p p y n e w y e a r !
}
Looping over a Set
A set is a collection of unique values.
const letters = new Set(['a', 'b', 'c'])
for (const letter of letters) {
console.log(letters) // a, b, c
}
Looping over a map
A map is key-value pair, where key can be of any type. In JavaScript it’s common to use object literals as maps
const details = new Map( [
['name', 'Michael Myers'],
['age', 45] // made up
])
// or a cleaner way:
const details = new Map()
details.set('name', 'Michael Myers')
for (const detail of details ) {
console.log(detail)
}
Summary
for...of
introduces a cleaner way of looping over arrays, sets, strings and maps.
Read more about 👉 Map objects