The Mozilla Developer Network has the following example of passing a value to next() and how it's captured by yield:
function* fibonacci() {
let current = 0;
let next = 1;
while (true) {
let reset = yield current;
[current, next] = [next, next + current];
if (reset) {
current = 0;
next = 1;
}
}
}
const sequence = fibonacci();
console.log(sequence.next().value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next().value); // 3
console.log(sequence.next().value); // 5
console.log(sequence.next().value); // 8
console.log(sequence.next(true).value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
What I'm confused about is the let reset = yield current; line. I understand that current will receive the value passed into next(). What I don't understand is why the if (reset) { /* ... */ } conditional won't evaluate to true once current is any value greater than 1.
It seems like the let reset = yield current; line is only evaluated if a value is passed into next(), but I'm not sure that's actually the case, let alone why it would be the case if so. The MDN docs gloss over what's actually going on here.
Further explanation would be greatly appreciated.
EDIT: Put another way, what does let reset = yield current; mean when a value is NOT passed into next()? Because current is still increasing in value with each run of the loop. Is the assignment simply not happening?