- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are generator functions in JavaScript?
Generator Functions allows execution of code in between when a function is exited and resumed later. So, generators can be used to manage flow control in a code. Cancel asynchronous operations easily since execution can be paused anytime.
Here’s the syntax; do not forget to add an asterisk after the “function” keyword. You can add an asterisk using any of the following −
function *myFunction() {} // or function* myFunction() {} // or function*myFunction() {}
Example
Let’s see how to use a generator function
<html> <body> <script> function* display() { var num = 1; while (num < 5) yield num++; } var myGenerator = display(); document.write(myGenerator.next().value); document.write("<br>"+myGenerator.next().value); document.write("<br>"+myGenerator.next().value); document.write("<br>"+myGenerator.next().value); document.write("<br>"+myGenerator.next().value); </script> </body> </html>
- Related Articles
- Explain Generator functions in JavaScript?
- What are async generator methods in JavaScript?
- What are functions in JavaScript?
- What are callback functions in JavaScript?
- What are immediate functions in JavaScript?
- What are Partial functions in JavaScript?
- What are JavaScript Math Functions?
- What are JavaScript Nested Functions?
- What are JavaScript Factory Functions?
- What are optional arguments in JavaScript Functions?
- What are Rest parameters in JavaScript functions?
- What are Self-Invoking Anonymous Functions in JavaScript?
- JavaScript Generator
- What are different ways of defining functions in JavaScript?
- Random color generator in JavaScript

Advertisements