DEV Community

Cover image for ES6: JavaScript for...of statement
Naftali Murgor
Naftali Murgor

Posted on

ES6: JavaScript for...of statement

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

Top comments (0)