> For the complete documentation index, see [llms.txt](https://strctr.gitbook.io/programming/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://strctr.gitbook.io/programming/01-languages/javascript/01-language/e-controls/e1-iteration/04-for-of-loop-es6.md).

# 04. for-of loop

`for-of` is a new loop in ES6 that replaces both `for-in` and `forEach()` that supports the new iteration protocol.

* Use it to loop over iterable objects (Arrays, strings, Maps, Sets).
* `for-of` goes through the items of iterable and assigns them, one at a time, to the loop variable, before it executes the body.
* The scope of loop variable is the loop, it only exists inside it.
* `break` and `continue` work inside for-of loops:

```javascript
// iterate over array
const iterable = ["a", "b"];
for (const x of iterable) {
  console.log(x);
}

// Iterate over map
const map = new Map([
  [false, "no"],
  [true, "yes"]
]);
for (const [key, value] of map) {
  console.log(`${key} => ${value}`);
}
```

The operand of the of clause must be iterable:

```javascript
// Array-like, but not iterable!
const arrayLike = { length: 2, 0: "a", 1: "b" };

for (const x of arrayLike) {
  // TypeError
  console.log(x);
}

for (const x of Array.from(arrayLike)) {
  // OK
  console.log(x);
}
```
