Mostafa Abdelraouf
Jan 31, 2016 · 4 min read

What are these “generators” anyway?

Generators is a new feature in ECMAScript 6. A generator is a “kind of” a function that contains the keyword “yield”, so the central piece in understanding what generators are and how they work is understanding the keyword “yield”.

A simple generator
Output of 5 calls to the generator in the code above
A “generator” that “generates” a number from 0 to 499 with each call to next()
The output of 2 calls to the generator in the code above

Do “generators” have other uses?

So this neat new feature is called “generators”, but don’t let the name fool you, the “yield” keyword and “generators” can be used for more than just “generating a sequence of values”, remember that at the most basic level the “yield” keyword is just about pausing and resuming the execution of a function.

A simplified view of an artificial neural network training loop
This code demonestrates the use of “yield” to control an iterative process

Mostafa Abdelraouf

Written by

A medical geek, Interested in Pathology, Computer Science and History, founder of @Alfehrest

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade