Generators
comparison between generators and regular functions, use case of a generator
A generator is a special function that returns an iterator. There are some differences between generator functions and regular functions:
- There is an
*
after thefunction
keyword. - Generator functions create iterators.
- We use the
yield
keyword in the created iterator function. By writingyield v
, the iterator returns{ value: v, done: false }
as a value. - We can also use the return keyword to end the iteration. Similar to iterators, the returned value won’t be enumerated by a data consumer.
- The yielded result is the next value of the iteration process. Execution of the generator function is stopped at the point of yielding. Once a data consumer asks for another value, execution of the generator function is resumed by executing the statement after the last yield.
Consider the following example:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.