ES6: JavaScript for...of statement
source link: https://dev.to/naftalimurgor/es6-javascript-forof-statement-2caa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
}
Enter fullscreen mode
Exit fullscreen mode
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 !
}
Enter fullscreen mode
Exit fullscreen mode
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
}
Enter fullscreen mode
Exit fullscreen mode
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)
}
Enter fullscreen mode
Exit fullscreen mode
Summary
for...of
introduces a cleaner way of looping over arrays, sets, strings and maps.
Read more about 👉 Map objects
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK