# only-iterate-once iterable

[JS](../..)⟩ [iteration](..) ⟩ [iterable]() ⟩ only-iterate-once iterable

{% hint style="danger" %}
some <mark style="color:yellow;">**iterables**</mark> <mark style="color:red;">**only iterate once**</mark>❗️
{% endhint %}

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="warning" %}
<mark style="color:orange;">**only-iterate-once**</mark>**&#x20;**<mark style="color:yellow;">**iterables：**</mark>

* [iterable](../iterator/iterable "mention")s - [iterator](../iterator "mention")s [iterators-only-iterate-once](../iterator/iterators-only-iterate-once "mention").
* [Broken link](broken-reference "mention")s - generators are **iterable iterators**.
* array.[keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys), map.[entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries), ... - built-in **iterable iterators**.
{% endhint %}
{% endtab %}

{% tab title="🗺️ 圖解" %}
<img src="https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FLDbsdTPR3ENAv8P81akq%2Fiteration-related-types.svg?alt=media&#x26;token=6c6da705-70d0-4fd6-97b8-5663b3d61f2d" alt="" class="gitbook-drawing">
{% endtab %}

{% tab title="💈範例" %}
:floppy\_disk: replit：[only iterate once](https://replit.com/@pegasusroe/only-iterate-once-iterable#index.js)

```javascript
// generator function returns "generators"
// - generators are "iterable iterators".
// - iterators only iterate once❗
function* genAB() {
    yield 'A';
    yield 'B';
}

// main
const ab = ['a', 'b'];     // array (iterable)
const it = ab.values();    // iterator (iterable)
const AB = genAB();        // generator (iterable iterator)

// ⭐ arrays can iterate multiple times.
[...ab, ...ab],            // [ 'a', 'b', 'a', 'b' ]

// ⭐ iterators only iterate once❗
[...it, ...it],            // [ 'a', 'b' ]❗
[...AB, ...AB],            // [ 'A', 'B' ]❗

// ⭐ have to call generator function multiple times
//    to return multiple new iterators.
[...genAB(), ...genAB()],  // [ 'A', 'B', 'A', 'B' ] ⭐
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] 2ality ⟩ [A downside of iterable iterators](https://2ality.com/2021/08/iteration-helpers.html#a-downside-of-iterable-iterators)
{% endtab %}
{% endtabs %}
