Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the yield keyword really work in JavaScript ES6 Generators? [duplicate]

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!

like image 940
Bruno Mazza Avatar asked Apr 17 '18 12:04

Bruno Mazza


People also ask

What does the yield statement in a generator do JavaScript?

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.

What are generators How does yielding work?

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.

Is yield a generator?

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'.

How do generators work in JavaScript?

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.


1 Answers

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]
like image 119
thgaskell Avatar answered Oct 16 '22 20:10

thgaskell