Iterators and Generators in JavaScript
Let's discover some hidden gems and not so commonly used concepts in JavaScript. Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of
loops.
Iterators
In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination.
It's an object with the following properties:
-
value
: Value held currently by the iterator. -
done
: A boolean flag to determine if the iterator has been consumed.
Generators
Generators are a special type of iterators returned by a Generator function. A generator has the following properties:
-
next()
: This method consumes the iterator and returns the next value. -
return(value: any)
: This method is used to mark the iterator as consumed and returns the value passed as the argument. -
throw(error: any)
: This method is used to throw an error passed as the argument.