0% found this document useful (0 votes)
5 views

Generator Function in Javascript

Generator functions in JavaScript can return multiple values one by one using the yield keyword, unlike regular functions which return a single value. When called, a generator function returns a generator object. The generator object's next() method runs the code until the next yield statement and returns the yielded value each time.

Uploaded by

marwan rzig
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Generator Function in Javascript

Generator functions in JavaScript can return multiple values one by one using the yield keyword, unlike regular functions which return a single value. When called, a generator function returns a generator object. The generator object's next() method runs the code until the next yield statement and returns the yielded value each time.

Uploaded by

marwan rzig
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

SAVE IT LIKE IT

GENERATOR FUNCTIONS IN
JAVASCRIPT

MADE BY
DEV_BHASKAR
SAVE IT LIKE IT

What are generator funtions?


Regular functions return only one,
single value (or nothing).

Generators can return (“yield”)


multiple values, one after another,
on-demand. They work great with
iterables, allowing to create data
streams with ease.

MADE BY
DEV_BHASKAR
SAVE IT LIKE IT

Generator Funtion: -
When a generator function is called it
returns a special object, called “generator
object”

MADE BY
DEV_BHASKAR
SAVE IT LIKE IT

The main method of a generator is next().


it runs the execution until the nearest
yield <value> statement

Generator object

MADE BY
DEV_BHASKAR
SAVE IT LIKE IT

Generator function using next :

Output :

MADE BY
DEV_BHASKAR
SAVE IT LIKE IT

Let’s call generator.next() again

NEW CALLS TO GENERATOR.NEXT() DON’T MAKE SENSE ANY MORE.

Now the generator is done. We should see it from


done:true and process value:3 as the final result.

after this they return the same object: {done: true}


MADE BY
DEV_BHASKAR

You might also like