close
The Wayback Machine - https://web.archive.org/web/20240912154108/https://www.geeksforgeeks.org/javascript-generator-next-method/
Open In App

JavaScript Generator next() Method

Last Updated : 23 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript Generator.prototype.next() method is an inbuilt method in JavaScript that is used to return an object with two properties done and value. 

Syntax:

gen.next( value );

Parameters: This function accepts a single parameter as mentioned above and described below:

  • value: This parameter holds the value to be sent to the generator.

Return value: This method returns an object containing two properties:

  • done: It has the value
    • true – for the iterator which is past the end of the iterated sequence.
    • false – for the iterator which is able to produce the next value in the sequence.
  • value: It contains any JavaScript value which is returned by the iterator.

The below examples illustrate the Generator.prototype.next() method in JavaScript: 

Example 1: In this example, we will create a generator and then apply the Generator.prototype.next() method and see the output.

javascript




function* GFG() {
    yield "GeeksforGeeks";
    yield "JavaScript";
    yield "Generator.prototype.next()";
}
  
const geek = GFG();
console.log(geek.next());
console.log(geek.next());
console.log(geek.next());
console.log(geek.next());


Output:

Object { value: "GeeksforGeeks", done: false }
Object { value: "JavaScript", done: false }
Object { value: "Generator.prototype.next()", done: false }
Object { value: undefined, done: true }

Example 2: In this example, we will create a generator and then apply the Generator.prototype.next() method and see the output.

javascript




function* GFG(len, list) {
    let result = [];
    let val = 0;
  
    while (val < list.length) {
        result = [];
        let i = val
        while (i < val + len) {
            if (list[i]) {
                result.push(list[i]);
            }
            i += 1
        }
  
        yield result;
        val += len;
    }
}
list = [
    'geeks1', 'geeks2', 'geeks3',
    'geeks4', 'geeks5', 'geeks6',
    'geeks7', 'geeks8', 'geeks9',
    'geeks10', 'geeks11'
];
  
let geek = GFG(4, list);
  
console.log(geek.next().value);
console.log(geek.next().value);
console.log(geek.next().value);
console.log(geek.next().value);


Output:

geeks1,geeks2,geeks3,geeks4
geeks5,geeks6,geeks7,geeks8
geeks9,geeks10,geeks11
undefined

Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

We have a complete list of Javascript Generator methods, to check those please go through the Javascript Generator Reference article.



Previous Article
Next Article

Similar Reads

Recipe Generator using Next.js
In this tutorial, we'll create a Recipe Generator App using Next.js, a React framework that allows users to generate random recipes. This type of application can be useful for people looking for new meal ideas or wanting to explore different cuisines. application fetches recipe data from API and displays it to the user. Output Preview: Let us have
4 min read
Build a Jokes Generator With Next JS and API
Jokes generator application using Next Js is an application where we are using the external API to fetch the jokes. This application has features to copy the jokes and when the user clicks on "Get a Joke" new jokes will be generated. Preview of final output: Let us have a look at how the final output will look like. Prerequisites:Introduction to Ne
4 min read
JavaScript Generator throw() Method
JavaScript Generator.prototype.throw() method is an inbuilt method in JavaScript that is used to resume the execution of a generator by throwing an error into it. Syntax: gen.throw(exception); Parameters: This function accepts a single parameter as mentioned above and described below: exception: This parameter holds the exception to be thrown. Retu
2 min read
JavaScript Generator return() Method
JavaScript Generator.prototype.return() method is an inbuilt method in JavaScript that is used to return the given value and finishes the generator. Syntax: gen.return( value ); Parameters: This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value to be returned. Return value: This method r
2 min read
How to pass variables to the next middleware using next() in Express.js ?
The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2] request.mydata = someData; -------&gt; let dataFromMiddleware1 = request.mydata; Installation of Express m
2 min read
Next.js next/head
In this article, we'll learn about the Head component in NextJS and see how the head component is SEO friendly. The Head component is a built-in component provided by NextJS. We can add any element like we were adding in the head component of HTML. If you know HTML and CSS well then NextJS will be easy for you to learn. To keep everything simple th
4 min read
When to use next() and return next() in Node.js ?
In Node.js, particularly when working with the Express framework, middleware functions play a crucial role in handling requests. Two commonly used patterns within these middleware functions are next() and return next(). Understanding when and how to use these can significantly affect the flow and functionality of your application. Table of Content
4 min read
Next.js Create Next App
In Next.js, the create next app command is used to automatically initialize a new NextJS project with the default configuration, providing a streamlined way to build applications efficiently and quickly. System Requirements: Node.js 12.22.0 or laterNPM 6.14.4 or later OR Yarn 1.22.10 or latermacOS, Windows, and Linux are supportedGetting started wi
3 min read
Next.js next/link
In Next.js, next/link component enables client-side navigation between pages, enhancing performance by prefetching linked pages. It simplifies routing in your application, making it seamless and efficient. Table of Content Next.js next/link ComponentBasic usage of 'next/link'Dynamic routing with 'next/link'ConclusionNext.js next/link ComponentThe n
4 min read
Next.js next/amp
AMP (Accelerated Mobile Pages) is a web component framework developed by Google that enables the creation of fast-loading web pages. Next.js supports AMP out of the box, allowing you to create AMP pages seamlessly. What is Next.js AMP?AMP is designed to improve the performance of web pages, particularly on mobile devices. By using a subset of HTML
3 min read
Next.js next.config.js File
The next.config.js file in a Next.js application is a configuration file used to customize and extend the behavior of Next.js. It allows developers to adjust various settings such as routing, environment variables, image optimization, and more to tailor the application to their specific needs. What is next.config.js?The next.config.js is a configur
3 min read
JavaScript Generator Reference
JavaScript Generator is used to allow us to define an iterative algorithm by writing a single function whose execution is not continuous. Generator Constructor &amp; Generator Objects Generator() Constructor: A generator constructor is defined as a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather
2 min read
What to understand the Generator function in JavaScript ?
Generators generate value on the fly which means whenever there is a need for that value then only it will be generated. It means the value is generated but not stored in memory so it takes less time to execute. It uses asterick (*) symbol after the keyword function i.e. function* to tell javaScript it is a generator function. The generator functio
4 min read
How to throw an error in an async generator function in JavaScript ?
In this article, we will try to understand how to throw an error in a synchronous (abbreviated as "async") generator function in JavaScript with the help of theoretical as well as coding examples. Let us first have a look into the following section which will show us the syntax for declaring an async generator function. Syntax: async function* func
2 min read
JavaScript Generator() Constructor
In JavaScript, there is no particular Generator() constructor but instead, we can use generator function declaration to construct a Generator object which is iterable as the Generator object is a subclass of the Iterable class. Generators are usually used to create functions that can be exited and re-entered. Syntax: function* gen(){ // Sample Code
1 min read
JavaScript Generator constructor Property
JavaScript Generator constructor property is used to return the Generator constructor function for the object. The function which is returned by this property is just the reference to this function, not a Generator containing the function’s name. The JavaScript number constructor, string constructor, and generator constructor return function Number
1 min read
Create an QR Code Generator Project using HTML CSS & JavaScript
In today's digital world, QR codes are widely used and provide a practical way to share information and access content with a quick scan. This deeply manually operated will show you step-by-step how to create a QR code generator from scratch using HTML, CSS, and JavaScript. This article will give you the knowledge necessary to develop an intuitive
3 min read
Number Sequences Generator using HTML CSS and JavaScript
In this article, we are going to implement a number sequence generator based on HTML, CSS, and JavaScript. In this program, we have three different types of sequences: the Fibonacci Series, the Prime Number Series, and the Even Odd Number Series. Preview of final output: Let us have a look at how the final output will look like. PrerequisitesHTMLCS
5 min read
YouTube Video Embed Code Generator Tool using HTML CSS and JavaScript
In this article, we will see How to create your own YouTube Video embed code generator tool using the basics of HTML, CSS, and JavaScript. With this tool, we can create responsive embed code for responsive video output on all devices. We can make use of this tool and add the generated code in Blogger, WordPress, Wix, Google Sites, custom websites,
4 min read
Design Random Color Generator using HTML CSS and JavaScript
The Random Color Generator application can Generate new and random colors each time the user clicks on the Generate Color button. The user has the feature to Copy the HEX and RGB code of the generated color for the application. There is Dark Mode functionality, through which the user can view the generated color in the Dark Mode also and can toggle
4 min read
OTP Generator and Validator Card using JavaScript & Tailwind CSS
OTP (One-Time Password) generator and validator built using Tailwind CSS and JavaScript allows users to generate a random OTP and validate it against the entered OTP. The application has a user-friendly interface for generating and validating OTPs using JavaScript for interactivity and Tailwind CSS for styling. Approach to create OTP Generator and
3 min read
Wikipedia Summary Generator Card using Tailwind CSS & JavaScript
The Wikipedia Summary Generator is a web application that utilizes Tailwind CSS, enabling users to search for a topic and receive a summary from Wikipedia. Users can input their topic of choice into the application's search field, click on the "Search" button to retrieve the summary, and then download the summary as a text file. In addition, the ap
3 min read
Build a Password Generator App with HTML CSS and JavaScript
In this article, we will build a password generator application using HTML, CSS, and JavaScript. This application will generate strong and secure passwords based on user preferences, such as password length and character types. It aims to provide a convenient tool for users to generate random passwords that are difficult to guess and enhance their
3 min read
How to create Password Generator Card using JavaScript and Tailwind CSS ?
The Password Generator is a web application built using Tailwind CSS and JavaScript. It allows users to generate random passwords based on their specified criteria such as the length and character types. Output Preview: Let us have a look at how the final card will look like. ApproachIntegrate the Tailwind CSS via CDN Link in your HTML code. Use di
3 min read
Color Pallete Generator using JavaScript
Color Palette Generator App using HTML CSS and JavaScript is a web application that enables use­rs to effortlessly gene­rate random color palettes, vie­w the colors, and copy the color codes to the­ clipboard with just a single click. There is also a search bar that allows the user to check different color themes for their specified color. Prerequi
4 min read
Navigating the Labyrinth: A Maze Generator Game Using HTML CSS & JavaScript
This article will help you make a simple yet interesting maze game, combining the power of HTML, CSS, and JavaScript to immerse the players. Let's explore the development of a maze generator game, where players can navigate through a new labyrinth with each refresh, thanks to the implementation of a Backtracking Algorithm. Preview Image: Approach:T
11 min read
Create a Quote Generator Web App with Pure JavaScript using an API
In this tutorial we are going to create a web app that fetches motivational and inspirational quotes using an API. Application Requirements: Bootstrap 4 CDNAPI : https://type.fit/api/quotesJavaScriptHTMLSteps: Follow the below steps to create a quote generator. Step 1 Fetch: We are using inbuilt fetch Function of JavaScript for fetching the data fr
3 min read
How to create a Color Generator using HTML CSS and JavaScript ?
In this article, we will develop a Color Generator application using HTML, CSS, and JavaScript. In this application, we have created the Multi Format color generator. Users can select Colour Types like RGB, HEX, and CMYK. Use the sliders to customize the color and Inout field in case of HEX and color picker to directly change the color with color i
6 min read
Design Joke Generator App in HTML CSS & JavaScript
We will go to learn how can we create a Joke generator app using HTML, CSS, and JavaScript. We will also add a feature to copy the generated joke. We will use API to fetch the jokes and will show those jokes on the screen. PrerequisitesHTMLCSSJavaScriptApproachCreate the Joke Generator Application UI Structure using HTML Elements like &lt;div&gt;,
3 min read
How to Check a Function is a Generator Function or not using JavaScript ?
Given an HTML document containing some JavaScript function and the task is to check whether the given function is generator function or not with the help of JavaScript. There are two examples to solve this problem which are discussed below: Example 1:In this example, we will use functionName.constructor.name property. It functionName.constructor.na
2 min read