Iterable protocol
Protocol characteristics
The
“Iterable protocol” is an agreed-upon APi at the level of JavaScript as a language, for creating objects that can be used to iterate over a collection of data. The key characteristic of this protocol is “sequentiality” ie. property that when iterating, it returns the value of the iterable structure one by one. Data types that satisfy the iterable protocol are called “iterable collections”. Respecting the iterable protocol, it is necessary that the function returns an object containing a special method “next()”.
next()
When called, the next() method returns a member of the collection temporarily “wrapped” (eng. wrapped”) with an object that has two properties: value and done. As long as there are members for iteration, the method returns the value of the “done” property as “false”, and only when the iteration “comes” to the end, the “done” property is defined as “true”.
Example
Through the following example, the concept of the protocol:
is described
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function arrayIterator(array) { var i = 0; return { next: function() { return i < array.length ? { value: array[i++], done: false } : { done: true }; } } } |
Which data types are iterable?
It should be emphasized that ordinary javascript objects are not iterable, but the following data types satisfy the iterable protocol:
- String
- Array
- Array-like arguments or NodeList object
- TypedArray
- Map
- Set
Which mechanisms in JavaScript require an iterable collection?
Mechanisms for the use of which “iterable” collections are necessary are:
- Destructuring
- for..of loop
- Array.from()
- Spread operator (…)
- Maps & Sets
- Promise.all(), Promise.race()
- yield*
Example
Iterable collections can use mechanisms that require iterable collections such as iteration with a “for..of” loop:
|
1 2 3 4 |
const array = [1, 2, 3, 4]; for(let elem of array) { console.log(elem); } |
or when destructing:
|
1 2 3 4 5 6 7 |
const nekaMapa = new Map([['key1', 1], ['key2', 2], ['key3', 3]]); for(let [key, value] of nekaMapa) { console.log(`${key}: ${value}`); } |
