๐ฐgenerator function
JS โฉ iteration โฉ generator function
defined by function* keyword and returns a Generator object.
use cases
generator function as ... (variable, method)
as make-iterator method of an iterable.
examples
*list() - sequence of numbers
composition of generator functions
yield and yield* operator can only be used within generator functionsโ๏ธ
replit๏ผyield must be in generator functions
// this seems like a generator function, but there's a catch ...
function* sequence(...iterables) {
// --------------------------------------------------------------
// โญ `yield/yield*` only available within generator functionsโ
// --------------------------------------------------------------
// โ but this `yield*` is within an "arrow function"โ
//
// โญโโโ ๐ธ arrow function โโโโฎ
iterables.forEach( iterable => yield* iterable );
// ^^^^^^
// โ ReferenceError: yield is not defined
}yield and yield* operator can only be used within generator functionsโ๏ธ
we can use generator functions to make iterables.
there is no way to write a generator function using arrow function syntax.
๐พ replit๏ผgenerator functions & objects
// โญ๏ธ generator function
function* abc() {
yield 'a';
yield 'b';
yield 'c';
}
// main
let str = '';
// โญ๏ธ for-of loop โญโโโโฎ ----> โญ๏ธ generator object
for (const char of abc()) {
str += char;
} // str = 'abc'objects returned by generator functions are iterable iterators.
function* (declaration) โญ๏ธ
Last updated
Was this helpful?