The JavaScript for...of statement iterates over the values of iterable objects such as Arrays, Strings, Maps, Sets, NodeLists, and more. It was introduced in ES6 to provide a clean and concise iteration mechanism.

Syntax

The for...of statement has the following syntax:

for (const value of iterable) {
  // code block to be executed
}

For each iteration, the value of the property is assigned to the value variable. It can be declared with const, let, or var. The iterable is the object which has enumerable properties (strings, arrays, maps, sets, etc.) and can be iterated upon. The code block is executed once for each property.

Examples

Let us look at the following examples that demonstrate how to use for...of statement to loop over different iterable objects.

Iterating over an array

A JavaScript array is a simple data structure that stores multiple values in a single variable. Here is an example that shows how you can iterate over an array using the for...of loop:

const birds = ['🐦', '🦅', '🦆', '🦉']

// iterate over all values
for (const bird of birds) {
  console.log(`Hey ${bird}`)
}

// Hey 🐦
// Hey 🦅
// Hey 🦆
// Hey 🦉

Iterating over a string

Strings are also an iterable data type, so you can use for...of on strings too:

const str = 'Cat'

// iterate over the string
for (const char of str) {
  console.log(char.toUpperCase().repeat(2))
}

// CC
// AA
// TT

Iterating over a Map object

A JavaScript Map is a special data structure introduced in ES6 that allows you to create collections of key-value pairs. Both objects and primitive values can be used as a key or value.

When iterating over the map, the for...of statement returns a key-value pair for each iteration in the same order as they were inserted as shown below:

const foods = new Map([
  ['🍌', 'Banana'],
  ['🍕', 'Pizza'],
  ['🥒', 'Cucumber']
])

// iterate over the map
for (const [key, value] of foods) {
  console.log(`${key}: ${value}`)
}

// 🍌: Banana
// 🍕: Pizza
// 🥒: Cucumber

Iterating over a Set object

A JavaScript Set is a special type of object introduced in ES6 that allows you to create a collection of unique values. You can store both objects and primitives as values in a set object.

The following example shows how you can use for...of to iterate over a set object:

const flowers = new Set(['🌷', '🌻', '🌹', '🌸']);

// iterate over the set
for (const flower of flowers) {
  console.log(flower);
}

// 🌷
// 🌻
// 🌹
// 🌸

Iterating over an arguments object

An arguments object is just an array-like object accessible inside functions that contains the values of the arguments passed to that function.

Using for...of loop, you can iterate over the arguments object to list all the arguments passed to a JavaScript function:

function animals() {
  for (const arg of arguments) {
    console.log(arg)
  }
}

animals('🐱', '🐧', '🐥', '🐯')

// 🐱
// 🐧
// 🐥
// 🐯

Iterating over a NodeList

The for...of statement can also be used to iterate over a DOM collection like a NodeList. The following example adds a img-fluid class to images that are direct children of an article:

// select all images
const images = document.querySelectorAll('article > img')

// iterate over NodeList
for (const img of images) {
  img.classList.add('img-fluid')
}

Iterating generators

A generator is a special kind of function in JavaScript that can be exited and later re-entered.

You can easily iterate over generators using the for...of statement as shown in the following example:

function* generator() {
  yield 1
  yield 2
  yield 3
}

// iterate over the generator
for (const gen of generator()) {
  console.log(gen)
}

// 1
// 2
// 3

Closing iterators

You can easily terminate a for...of loop and close the iterator by using break, return, or throw statement:

const digits = [1, 2, 3]

for (const d of digits) {
  console.log(d)
  // terminate loop
  break
}

console.log('Done')

// 1
// Done

Iterating over an object literal

Unfortunately, for...of only works with iterables. An object literal is not iterable. However, you can use the Object.keys() method to get all property names and then iterate over them:

const animals = {
  tiger: '🐅',
  cat: '🐱',
  monkey: '🐒',
  elephant: '🐘'
}

for (const key of Object.keys(animals)) {
  console.log(`${key} -> ${animals[key]}`)
}

// tiger -> 🐅
// cat -> 🐱
// monkey -> 🐒
// elephant -> 🐘

Instead of using for...of statement, you should consider using for...in loop for object literals.

Browser compatibility

JavaScript for...of statement is currently supported by modern browsers only. If you want to support old browsers like Internet Explorer, you need a polyfill or use the forEach() loop instead.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.