ES6: JavaScript for...of statement
Naftali Murgor
Posted on January 18, 2022
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 (fruit of fruits) {
// do something with fruit
}
Looping over a string
for...of
can also be used to loop over contents of a string.
const words = 'Happy new year!'
for (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 (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 (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
💖 💪 🙅 🚩
Naftali Murgor
Posted on January 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.