---
title: "What are generators in JavaScript and how do you use them?"  
description: "What are generators in JavaScript and how do you use them?"  
author: "Utpal Vishwas"  
published: 2023-05-16  
updated: 2023-05-16  
canonical: https://www.mindstick.com/forum/158345/what-are-generators-in-javascript-and-how-do-you-use-them  
category: "javascript"  
tags: ["javascript", "javascript object"]  
reading_time: 2 minutes  

---

# What are generators in JavaScript and how do you use them?

What are [generators](https://www.mindstick.com/articles/310568/buying-guide-for-generators) in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript) and how do you use them?

## Replies

### Reply by Aryan Kumar

Generators are a special type of function that can be paused and resumed. They are created using the function* keyword.

Generators are useful for tasks that need to be performed repeatedly, such as iterating over a large data set. They can also be used to implement asynchronous code, such as code that makes HTTP requests.

To use a generator, you first need to create it. You can do this using the function* keyword.

Once you have created a generator, you can start iterating over it using the next() method. The next() method will return the next value from the generator, or undefined if there are no more values.

You can also use the yield keyword to yield a value from the generator. The yield keyword will pause the generator and return the value to the caller. The generator will then resume at the next call to next().

Here is an example of a generator that iterates over a list of numbers:

Code snippet

```plaintext
function* generateNumbers() {
  for (let i = 0; i < 10; i++) {
    yield i;
  }
}

const numbers = generateNumbers();

for (let number of numbers) {
  console.log(number);
}
```

This code will print the numbers 0 to 9.

Generators can also be used to implement asynchronous code. Here is an example of a generator that makes an HTTP request:

Code snippet

```plaintext
function* getRequest(url) {
  const response = await fetch(url);
  const data = await response.json();
  yield data;
}

const data = await getRequest('https://api.github.com/users/bard');

console.log(data);
```

This code will make an HTTP request to the GitHub API and print the user information for the user with the username "bard".

Generators are a powerful tool that can be used to improve the performance and readability of your code. They are especially useful for tasks that need to be performed repeatedly or for implementing asynchronous code.


---

Original Source: https://www.mindstick.com/forum/158345/what-are-generators-in-javascript-and-how-do-you-use-them

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
