9-ES6++: Generators
Tags: javascript, es6, esnext
Published: 2022-11-19 07:09:23

---
title: 9-ES6++: Generators
published: true
description: 
series: es6++
tags: javascript, es6, esnext
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fekj2d9sx23jf0hd2uzq.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

## Generators

In **ES6** we have a new type of function, which is called `generator`. A generator is a function that can be paused and resumed, which means that a generator can produce a sequence of values

## Creating a generator

To create a generator, we use the `function*` syntax:

```js
function* generator() {
  yield 1;
  yield 2;
  yield 3;
}
```

Here we defined a generator called `generator`, that generator contains three `yield` statements. A `yield` statement is used to pause the generator and return a value.

## Using a generator

To use a generator, we call it like a normal function:

```js
const gen = generator();
```

Then we can use the `next()` method to get the next value from the generator:

```js
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
```

As we can see, the `next()` method returns an object with two properties, `value` and `done`. The `value` property contains the value that was returned from the generator, and the `done` property is a boolean that indicates if the generator has finished or not.

## Using a generator with a for...of loop

We can use a generator with a `for...of` loop to get all the values from the generator:

```js
for (const value of generator()) {
  console.log(value); // 1, 2, 3
}
```

## Using a generator with the spread operator

We can use a generator with the `spread` operator to get all the values from the generator:

```js
console.log(...generator()); // 1 2 3
```

## What is the purpose of using generators?

Generators are useful when we want to produce a sequence of values, for example, we can use a generator to produce a sequence of numbers:

```js
function* numbers() {
  let i = 0;
  while (true) {
    yield i++;
  }
}
```

Here we defined a generator called `numbers`, that generator contains an infinite loop, and in each iteration we yield the value of `i` and then increment it.

Now we can use the `numbers` generator to get a sequence of numbers:

```js
const gen = numbers();
console.log(gen.next()); // { value: 0, done: false }
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
```

It will keep producing numbers forever.

## Real World Example in Javascript

Let's see a real world example of using generators in Javascript. We will use generators to create a `range` function, that will produce a sequence of numbers:

```js
function* range(start, end) {
  for (let i = start; i <= end; i++) {
    yield i;
  }
}
```

Here we defined a generator called `range`, that generator contains a `for` loop, and in each iteration we yield the value of `i`.

Now we can use the `range` generator to get a sequence of numbers:

```js
for (const value of range(1, 5)) {
  console.log(value); // 1, 2, 3, 4, 5
}
```

## But why not using a normal function?

We can use a normal function to produce a sequence of numbers:

```js
function range(start, end) {
  const result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
}
```

Here we defined a function called `range`, that function contains a `for` loop, and in each iteration we push the value of `i` to the `result` array.

Now we can use the `range` function to get a sequence of numbers:

```js
console.log(range(1, 5)); // [1, 2, 3, 4, 5]
```

So why not using a normal function instead of a generator? The answer is that generators are lazy, which means that they don't produce all the values at once, they produce the values only when we need them.

Which means that if we have a very `large sequence` of numbers, we can use a generator to produce the numbers one by one, instead of producing all the numbers at once.

This will reduce the memory usage, and will make our code more efficient.

## 🎨 Conclusion

In this article, we talked about generators, and how to use it and why we should use it.

## ☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may [buy me a coffee](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) to get help and support (Node Js 2023 Channel).

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)