Generators
The Generators are a special type of function in JavaScript that can be paused and resumed during their execution. They are defined using the asterisk (*) after the function keyword. The Generators use the yield keyword to yield control back to the caller while preserving their execution context. The Generators are useful for creating iterators, asynchronous code, and handling sequences of data without loading all the data into the memory at once.
Example: In this example, we will see a simple generator function that yields values in the sequence.
Javascript
function * GFG() { yield 10; yield 20; yield 30; } const generator = GFG(); console.log(generator.next().value); console.log(generator.next().value); console.log(generator.next().value); |
10 20 30