Generators
In this lesson you’ll learn all about generators and what to do with them.
What is a generator? #
A generator function is a function that we can start and stop, for an indefinite amount of time. And also restart with the possibility of passing additional data at a later point in time.
To create a generator function we write like this:
Press + to interact
function* fruitList(){yield 'Banana';yield 'Apple';yield 'Orange';}const fruits = fruitList();fruits;// Generatorconsole.log(fruits.next());// Object { value: "Banana", done: false }console.log(fruits.next());// Object { value: "Apple", done: false }console.log(fruits.next());// Object { value: "Orange", done: false }console.log(fruits.next());// Object { value: undefined, done: true }
Let’s have a look at the code piece by piece:
- we declared the function using
function*
- we used the keyword
yield
before our content - we start our function using
.next()
- the
Access this course and 1400+ top-rated courses and projects.