# How to use for...of loop in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Feb 20, 2020, updated Oct 9, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-for-of-loop

> An introduction to JavaScript for...of loop and how to use it to iterate through different iterable  objects.

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:

```javascript
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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/maps-javascript) 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:

```javascript
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](https://attacomsian.com/blog/sets-javascript) 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:

```javascript
const flowers = new Set(['?', '?', '?', '?']);

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

// ?
// ?
// ?
// ?
```

### Iterating over an `arguments` object

An [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/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:

```javascript
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`](https://attacomsian.com/blog/javascript-nodelist). The following example adds a `img-fluid` class to images that are direct children of an article:

```javascript
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) 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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/javascript-object-property-shorthand) is not iterable. However, you can use the `Object.keys()` method to get all property names and then iterate over them:

```javascript
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](https://attacomsian.com/blog/for-in-loop-in-javascript) 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()](https://attacomsian.com/blog/javascript-foreach) loop instead.
