0% found this document useful (0 votes)
4 views1 page

Q23 What is Generator Function in JavaScript

A generator function in JavaScript allows functions to pause and resume execution, making them useful for lazy evaluation and asynchronous programming. An example is provided with a simple number generator that yields values sequentially. Additionally, an infinite ticket generator demonstrates how to create an ongoing sequence of values.

Uploaded by

shekharbarla9966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Q23 What is Generator Function in JavaScript

A generator function in JavaScript allows functions to pause and resume execution, making them useful for lazy evaluation and asynchronous programming. An example is provided with a simple number generator that yields values sequentially. Additionally, an infinite ticket generator demonstrates how to create an ongoing sequence of values.

Uploaded by

shekharbarla9966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Q. What is generator function in JavaScript?

A generator function is a powerful feature in JavaScript that allows functions to


pause and resume execution, making them useful for lazy evaluation, iterating
over sequences, or asynchronous programming when used with async/await.
Example:

function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}

const gen = numberGenerator();

console.log(gen.next()); // { value: 1, done: false }


console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }

Realtime Example:
Infinite ticket generator

function* infiniteCounter() {
let i = 1;
while (true) {
yield `Ticket-${i++}`;
}
}

const counter = infiniteCounter();


console.log(counter.next().value); // Ticket -1
console.log(counter.next().value); // Ticket -2

You might also like