JavaScript Iterators and Generators for Pythonistas (Summary)

Congratulations, you made it to the end of the course! Priya’s weather station feed now runs in JavaScript, and it stays lazy from the sensor to the dashboard. At the start, the port with array methods read all six readings to show the first two, while Python’s islice() stopped after two.

Here’s the same job in the finished port. The valid() generator logs each reading, and the iterator helpers take the first two:

Language: JavaScript
const readings = [12.5, 13.1, null, 14.0, 13.6, 15.2];

function* valid(values) {
  for (const value of values) {
    console.log("read", value);
    if (value !== null) yield value;
  }
}

console.log(valid(readings).take(2).toArray());

JavaScript now stops after two readings, as Python did:

Language: Program Output
read 12.5
read 13.1
[ 12.5, 13.1 ]

Getting there meant finding a JavaScript home for the iterator class, the generators, the itertools calls, and the async for loop in Priya’s Python service.

In this course, you learned how to:

  • Write the full iteration protocol by hand, so for...of walks an iterator you wrote yourself
  • Use function* generators to write iterators, and send values into them
  • Chain lazy iterator helpers, such as .drop() and .take(), on an iterator
  • Find JavaScript equivalents for the itertools functions you use
  • Consume async feeds with for await...of

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.