Search code examples
javascriptarraysecmascript-6iterable

Convert Array to ES6 Iterable


I have found the answer to: Convert ES6 Iterable to Array

But I'm looking for the opposite:

How can I convert an Array like ['something', 'another thing'] to an ES6 Iterable?


Solution

  • An Array already is an ES6 iterable.

    "Iterable" is a capability that a number of different types of objects can have and an Array has that capability built-in (as of ES6).

    For example, you can directly use the iterator capabilities with something like:

    for (let item of ['something', 'another thing']) {
         console.log(item);
    }
    

    Or, you could directly get the iterator with this:

    const myIterator = ['something', 'another thing'].entries();
    console.log(myIterator.next().value);