Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of yield without comma

I'm studying generator of javascript ES6.

While I try to understand an example of my book, I got trouble because of an array of yield without comma in below code.

How does this code work?

[ code ]

let gen = function*(){
    return [yield yield]; // how this code line works?
}
let genObj = gen();
console.log(genObj.next());
console.log(genObj.next(10));
console.log(genObj.next(20));

[ run result ]

Object {value: undefined, done: false}
Object {value: 10, done: false}
Object {value: Array[1], done: true}

[ test - 1 ]

let gen = function*(){
    return ['a' 'b'];
}
// Uncaught SyntaxError: Unexpected string

[ test - 2 ]

let a = [yield yield]

// Uncaught SyntaxError: Unexpected identifier
like image 970
Jay Lim Avatar asked Jun 29 '26 14:06

Jay Lim


2 Answers

I'm just gonna focus on your first example for this answer:

return [yield yield];

This line runs from right to left. The right-most yield sends a value of undefined to the caller of the iterator (that's what genObj is -- an iterator). On the line where you call genObj.next(10), you're passing 10 into the function gen() and resuming its execution at the right-most yield, as if the yield becomes 10:

return [yield 10];

Now the the console logs 10 since that's the next value you yield. And then you pass in 20 so in effect the function resumes as if:

return [20];

so the last return value that gets logged is an array of length === 1 containing the value 20.

like image 165
Patrick Roberts Avatar answered Jul 01 '26 04:07

Patrick Roberts


Your code is equivalent to the following:

let gen = function*(){
    let x = yield;
    let y = yield x;
    return [y];
}
let genObj = gen();
console.log(genObj.next());
console.log(genObj.next(10));
console.log(genObj.next(20));

[yield yield] is not an array without a comma between elements, it's an array of a single element, the expression yield yield.

yield yield evaluates the right yield first. It has no argument, so it returns undefined from the first call to .next(). The second .next() passes 10 in, which becomes the result value of yield.

This 10 is passed to the second yield, showing up as the return value of the second .next() call. The third .next() call passes 20 in, which becomes the result value of the second yield.

The function then wraps this 20 in an array [ ] and returns it.

like image 34
melpomene Avatar answered Jul 01 '26 03:07

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!