Range Over Iterators in JavaScript
Starting with version 1.23, support for iterators has been added, allowing us to iterate over almost anything!
Let’s look at the List
type again. Previously, a List
would return a slice of all its elements via an AllElements
method. We can improve it using iterators.
All returns an iterator, which in JavaScript can be implemented using generator functions.
The iterator function can yield every element we want to iterate over, and we can stop iteration using the break
statement.
Iteration doesn’t require an underlying data structure and doesn’t even have to be finite! Here’s a generator function for Fibonacci numbers that keeps running as long as the break
statement isn’t triggered.
With the List implementation, you can now create a list, push values to it, and iterate over them using the for...of
loop.
Since List.all
returns an iterator, it can be used in a regular for...of
loop.
List all its values using the for...of
loop. This collects all values from the all
iterator.
Next example: Errors.