Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created June 3, 2025 16:33
Show Gist options
  • Save rauschma/ac3133b5814a8b3d09e833df062b0d1d to your computer and use it in GitHub Desktop.
Save rauschma/ac3133b5814a8b3d09e833df062b0d1d to your computer and use it in GitHub Desktop.

Creating synchronous iterators

The methods of class Iterator let us process data incrementally. Let’s explore where we can use them.

Getting iterators from iterables
  • Iterator.from(iterable) always returns instances of Iterator (converting non-instances to instances as needed).
  • iterable[Symbol.iterator]() returns an iterator:
    • With all built-in data structures, the result is an instance of Iterator.
    • With other, older iterable objects, the result may not be an instance of Iterator.
Built-in methods that return iterators

Arrays, Typed Arrays, Sets and Maps have additional methods that return iterators:

  • Arrays (similarly: Typed Arrays):
    • Array.prototype.keys() returns an iterator over numbers.
    • Array.prototype.values() returns an iterator.
    • Array.prototype.entries() returns an iterator over key-value pairs. The keys are numbers.
  • Sets:
    • Set.prototype.values() returns an iterator.
    • Set.prototype.keys() returns an iterator. Equivalent to .values().
    • Set.prototype.entries() returns an iterator over value-value pairs (i.e., both components of the pair are the same value).
  • Maps:
    • Map.prototype.keys() returns an iterator.
    • Map.prototype.values() returns an iterator.
    • Map.prototype.entries() returns an iterator over key-value pairs.

The following methods return iterators:

  • String.prototype.matchAll() returns an iterator over match objects.
Other sources of iterators

Generators also return iterators:

function* gen() {}

assert.equal(
  gen() instanceof Iterator,
  true
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment