Creating Infinite Iterators

Learn how to use a generator to iterate over an infinite sequence with an example.

Iterators in JavaScript are inherently lazy. They yield a value, wait for it to be consumed by the caller, and then, when requested for more, go on to produce the next value. While we can yield values from a known collection of data, we can also exploit this flexibility to create infinite sequences of data.

Creating an infinite sequence of prime numbers

As an example, let’s create an infinite sequence of prime numbers.

As a first step, we’ll define an isPrime() function that will tell us whether a given number is a prime number.

Get hands-on with 1200+ tech skills courses.