© Russ Ferguson and Keith Cirkel 2017

Russ Ferguson and Keith Cirkel, JavaScript Recipes, 10.1007/978-1-4302-6107-0_13

13. Working with Generators

Russ Ferguson and Keith Cirkel2

(1)Ocean, New Jersey, USA

(2)London, UK

How Do You Create a Generator?

Problem

You want to know what a generator is and how you make one.

Solution

Generators are functions that do not immediately execute when called on. They return an iterator object that lets you call and pass parameters at another time. You can continue to call this function until the first yield expression is executed.

The Code

Listing 13-1. Creating a Generator
function * helloGenerator(){        yield 'HELLOFRIEND';}var sayHello- = helloGenerator();        console.log(sayHello) //returns generator        //console.log(sayHello.next()) ...

Get JavaScript Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.