> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/iteration/iterator/iterators-only-iterate-once.md).

# iterators only iterate once❗️

[JS](/web/js.md)⟩ [iteration](/web/js/iteration.md) ⟩ [iterator](/web/js/iteration/iterator.md) ⟩ only iterate once

{% hint style="danger" %}
[iterator](/web/js/iteration/iterator.md)s <mark style="color:yellow;">**only iterate once**</mark>❗️
{% endhint %}

{% tabs %}
{% 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 %}

{% tab title="👥 相關" %}

* [only-iterate-once iterable](/web/js/iteration/iterable/only-iterate-once.md)
  {% endtab %}
  {% endtabs %}
