I'm tackling Generators in ES6, and I would like to understand, conceptually, what's happening in the function below:
function* createNames() {
const people = [];
people.push(yield);
people.push(yield);
people.push(yield);
return people;
}
const iterator = createNames();
iterator.next('Brian');
iterator.next('Paul');
iterator.next('John');
iterator.next(); // output: ["Paul", "John", undefined]
My question is: why does the first push is ignored? Shouldn't the array be something like people = ['Brian', 'John', 'Paul', undefined]
? Sorry for the silly question, but I would really love to be able to fully grasp this. Thanks in advance!
In JavaScript, yield is used to pause the execution of a function. When the function is invoked again, the execution continues from the last yield statement. A generator returns a generator object, which is an iterator. This object generates one value at a time and then pauses execution.
It returns only a single value to the caller, and the code execution stops as soon as it reaches the return statement. When a caller calls the generator function, the first yield is executed, and the function stops. It then returns the generator object to the caller where the value is stored.
Since the yield enables the function to remember its 'state', this function can be used to generate values in a logic defined by you. So, it function becomes a 'generator'.
In ECMAScript 2015, generators were introduced to the JavaScript language. A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a generator function, which returns an iterable Generator object.
Invoking createNames()
does not execute any of the code inside of the generator. It creates an instance of an iterator, and execution begins on the first next()
call.
const iterator = createNames();
// Iterator instance created, but hasn't executed yet.
iterator.next('Brian');
// creates the people array
// attempts to push, yields
iterator.next('Paul');
// pushes 'Paul'
// attempts to push, yields
iterator.next('John');
// pushes 'John'
// attempts to push, yeilds
iterator.next();
// pushes undefined
// returns ["Paul", "John", undefined]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With