View profile

Iterators in JavaScript

Iterators were a new concept introduced with ES6 in 2015. An iterator is an object with a `next()` fu
Iterators in JavaScript
By Mastering JS Weekly • Issue #22 • View online
Iterators were a new concept introduced with ES6 in 2015. An iterator is an object with a `next()` function that returns an object with two properties: `value` and `done`.

Description of iterators from MDN
Description of iterators from MDN
For example, the below example has a plain old JavaScript object `iterator` that has `next()` function.
A basic iterator
A basic iterator
Iterators by themselves are typically not very useful. As a JavaScript developer you’re more likely to use the related concept of an iterable. An iterable is an object that has a `Symbol.iterator` function which returns an iterator.
Arrays have a `Symbol.iterator` function that returns an iterator
Arrays have a `Symbol.iterator` function that returns an iterator
In other words, an iterable is an object that has a function for creating a new iterator. What makes iterables interesting is that you can throw any iterable into a for/of loop:
Custom iterable works with for/of loops!
Custom iterable works with for/of loops!
Another interesting aspect of iterables is that, unlike with arrays, you don’t have to have all the values that you’re looping over in memory at once. For example, you can loop over all fibonacci numbers with a for/of loop, but only holding 3 of them in memory at a time:
Using a for/of loop to iterate the Fibonacci sequence
Using a for/of loop to iterate the Fibonacci sequence
The Fibonacci sequence is a toy example, not very useful in practice. But using a similar pattern with async iterators means that you can iterate over a database collection with tens of millions of entries using a `for/await/of` loop.
Most Recent Tutorials
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue