You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
When we declare a generator function with argument this argument will be passed only once when we execute the function and it returns iterator, and will be available during all calls of`next`
The rule of arguments passed to`next` method is that, the argument will replace the previous`yield` expression, this means that passing an argument to the first`next` call will simply be ignored!
222
+
223
+
####Example 14.6
224
+
225
+
```javascript
226
+
function*myGeneratorFunction() {
227
+
constx=yield1;
228
+
console.log(`x =${x}`);
229
+
consty=yield2;
230
+
console.log(`y =${y}`);
231
+
}
232
+
233
+
constmyIterable=myGeneratorFunction();
234
+
235
+
console.log(myIterable.next());
236
+
console.log(myIterable.next());
237
+
console.log(myIterable.next());
238
+
239
+
// { value: 1, done: false}
240
+
// x = undefined
241
+
// { value: 2, done: false}
242
+
// y = undefined
243
+
// { value: undefined, done: true}
244
+
```
245
+
246
+
As we can see from previous example, both values`x` and`y` are`undefined` because whenever we call`next` (starting from second call of`next`) the previous yield will be set to that argument, and since we don't pass anything the previous yield is set to`undefined`
247
+
248
+
####Example 14.7
249
+
250
+
This is a copy of example 14.6 but we will make sure to pass values while calling`next` method
251
+
252
+
```javascript
253
+
function*myGeneratorFunction() {
254
+
constx=yield1;
255
+
console.log(`x =${x}`);
256
+
consty=yield2;
257
+
console.log(`y =${y}`);
258
+
}
259
+
260
+
constmyIterable=myGeneratorFunction();
261
+
262
+
console.log(myIterable.next(22));
263
+
console.log(myIterable.next(33));
264
+
console.log(myIterable.next(44));
265
+
266
+
// { value: 1, done: false}
267
+
// x = 33
268
+
// { value: 2, done: false}
269
+
// y = 44
270
+
// { value: undefined, done: true}
271
+
```
272
+
273
+
As we can see from previous example
274
+
275
+
1. 22 passed in first`next` call is completely ignored
276
+
2. 33 replaced the entire previous`yield 1` expression which means x is set to 33
277
+
3. 44 replaced the entire previous`yield 2` expression which means y is set to 44
278
+
279
+
From previous example we can also track easily the behaviour of generator function execution and where exactly it will pause.
280
+
281
+
1. on execution of this line`myIterable.next(22)` generator function will`yield 1` and pause execution, even the assignment of x is not done
282
+
2. on execution of this line`myIterable.next(33)` generator function will assign`33` to`x` and will`yield 2` and pause, even the assignment of y is not done
283
+
3. on execution of this line`myIterable.next(44)` generator function will assign`44` to`y` and will return`{ value: undefined, done : true}`