Iterables In Javascript

Iterators are a way to loop over any collection in JavaScript. An iterable is a data structure that makes its collection of elements accessible by using an iterator. An iterator is a pointer for traversing the elements of the iterable data structure. If you’ve used the for-of loop you’re using an iterable. Destructuring, which we’ve written about previously is possible because of iterables. Check the link in the bio for more info and swipe through to see some examples.

Let’s check some of what is written out above with some examples. If we have an array we can explicitly access each element in that array by access the Symbol.iterator property which gives us back a function to be able to call each element:

const myNumbers = [1, 2, 3, 4];
const numberIterator = myNumbers[Symbol.iterator]();
numberIterator.next();
> {value: 1, done: false}
numberIterator.next();
> {value: 2, done: false}
numberIterator.next();
> {value: 3, done: false}
numberIterator.next();
> {value: 4, done: true}
numberIterator.next();
> {value: undefined, done: true}

As we mentioned with destructuring, you can access an element of an array:

const collection = ['foo', 'bar', 'cat'];

const [firstD] = collection;

// is equivalent to

const iterator = collection[Symbol.iterator]();
const firstI = iterator.next().value;

Read more about it in the You Don’t Know JS book and read an article on Mozilla

Instagram Post