JavaScript Iterables
An iterable is an object whose values can be accessed one at a time.
Iterables can be used in for...of loops, spread syntax, and many built-in JavaScript methods.
Why Iterables Matter
Many JavaScript features work with iterable objects.
Examples include:
for...of- Spread syntax (
...) Array.from()new Map(iterable)new Set(iterable)Promise.all()
Built-in Iterables
Several built-in JavaScript types are iterable.
| Type | Iterable |
|---|---|
| Array | Yes |
| String | Yes |
| Map | Yes |
| Set | Yes |
| TypedArray | Yes |
| WeakMap | No |
| WeakSet | No |
| Object | No |
Iterating Arrays
Arrays are iterable.
Example
const cars = ["Volvo", "Saab", "BMW"];
let text = "";
for (const car of cars) {
text += car + "<br>";
}
Iterating Strings
Strings are iterable.
Example
const text = "Hello";
for (const letter of text) {
console.log(letter);
}
Spread Syntax
Spread syntax works with iterable objects.
Example
const letters = [..."Hello"];
The result is:
["H", "e", "l", "l", "o"]
Array.from()
The Array.from() method creates an array from an iterable.
Example
const arr = Array.from("Hello");
The result is:
["H", "e", "l", "l", "o"]
Map and Set Constructors
The Map() and Set() constructors accept iterables.
Creating a Set
Example
const letters = new Set(["a", "b", "c"]);
Creating a Map
Example
const fruits = new Map([
["apples", 500],
["bananas", 300]
]);
Objects Are Not Iterable
Ordinary objects are not iterable.
Example
const person = {
name: "John",
age: 50
};
for (const value of person) {
console.log(value);
}
The example throws a TypeError.
Making Objects Iterable
Objects can become iterable by implementing the iterator protocol.
This is done by defining a Symbol.iterator method.
Example
const obj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
The Iterator Protocol
An iterable object has a Symbol.iterator method.
This method returns an iterator object.
The iterator object provides values one at a time.
Iterable
↓
Symbol.iterator()
↓
Iterator
↓
next()
↓
Value
Summary
| Type | Iterable | Common Use |
|---|---|---|
| Array | Yes | for...of, spread |
| String | Yes | for...of, spread |
| Map | Yes | for...of |
| Set | Yes | for...of |
| Object | No | Use Object.keys() |
| WeakMap | No | Not iterable |
| WeakSet | No | Not iterable |