🔰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❗️
// 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
objects returned by generator functions are iterable iterators.
function* (declaration) ⭐️
Last updated
Was this helpful?