JavaScript generator functions

In C# we have iterators which might return data, such as a collection but can also yield return values allowing us to more dynamically return iterable data.

Yield basically means return a value but store the position within the iterator so that when the iterator is called again, execution starts at the next command in the iterators.

These same type of operations are available in JavaScript using generator functions. Let’s look at a simple example

function* generator() {
  yield "A";
  yield "B";
  yield "C";
  yield "D";
}

The function* denotes a generator function and it’s only in the generator function we can use the yield keyword.

When this function is called a Generator object is returned which adheres to the iterable protocol and the iterator protocol which basically means, the Generator acts like an iterator.

Hence executing the following code will result in each yield value being output, i.e. A, B, C, D

for(const element of generator()) {
  console.log(element);
}