FrontendDeveloper.in

ECMAScript question detail

Generators

A generator is a function that can stop or suspend midway and then continue from where it stopped while maintaining the context(saved across re-entrances). It can be defined using a function keyword followed by an asterisk(i.e, function* ()).

This function returns an iterator object and this iterator's next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value.

function* myGenerator(i) {
yield i + 10;
yield i + 20;
return i + 30;
}

const myGenObj = myGenerator(10);

console.log(myGenObj.next().value); // 20
console.log(myGenObj.next().value); // 30
console.log(myGenObj.next().value); // 40

Note: We can use yield* to delegate to another generator function

Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399