---
title: "Introduction to ES6 generators"
description: "In this blog, we will explore ES6 generators with examples."
canonical_url: "https://www.bigbinary.com/blog/introduction-to-es6-generators"
markdown_url: "https://www.bigbinary.com/blog/introduction-to-es6-generators.md"
---

# Introduction to ES6 generators

In this blog, we will explore ES6 generators with examples.

- Author: Arbaaz
- Published: August 1, 2016
- Categories: JavaScript

**Generators** in JavaScript are the functions that can be **paused** and
**resumed**.

```javascript
function* genFunc(){...}
```

Calling `genFunc()` _doesn't execute the body_ of the function.

```javascript
const genObj = genFunc();
```

Instead, it returns **generator object** which can be used to control the
execution of the generator.

`genObj.next()` will start executing the function and it will execute **till**
it reaches `yield` keyword.

We can think of `yield` as `return for now`. It is similar to C#
[yield](https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx).

```javascript
function* genFunc() {
  console.log("First");
  yield;
  console.log("Second");
}
const genObj = genFunc();
genObj.next();

/*
output

First
*/
```

Calling `genObj.next()` again will **resume** the further execution after yield.

```javascript
function* genFunc() {
  console.log("First");
  yield;
  console.log("Second");
}
const genObj = genFunc();
genObj.next();
genObj.next();

/*
output

First
Second
*/
```

Here's how the execution looks like:

![Generator](https://www.bigbinary.com/blog/images/images_used_in_blog/2016/introduction-to-es6-generators/generator.gif)

`yield` is not allowed inside non-generator functions. That is, yielding in
callbacks doesn't work.

We can also pass the data to generator function via `next`.

```javascript
function* genFunc() {
  console.log("First");
  const input = yield;
  console.log(input);
  console.log("Second");
}
const genObj = genFunc();
genObj.next();
genObj.next("Third");

/*
output

First
Third
Second
*/
```

We can retrieve the yielded values via the generator object `genObj`:

```javascript
function* genFunc() {
  console.log("First");
  const input = yield;
  console.log(input);
  console.log("Second");
  yield "Forth";
}
const genObj = genFunc();
genObj.next();
const result = genObj.next("Third");
console.log(result);

/*
output

First
Third
Second
{
  done: false,
  value: "Forth"
}
*/
```

We can have multiple `yield` in the function as shown in the above example.

Once, the execution of the generator function is completed, further calls to
`genObj.next()` will have **no effect**.

### Further reading

We highly recommend
[Exploring ES6](http://exploringjs.com/es6/ch_generators.html) by Dr. Axel
Rauschmayer to go deeper on this topic.

## Links

- [Human page](https://www.bigbinary.com/blog/introduction-to-es6-generators)
