- 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
Explain Generator functions in JavaScript?
Generators
JavaScript supports Generator functions and Generator Objects. A generator function is the same as a normal function, but whenever it needs to generate a value it uses the 'yield' keyword rather than 'return'. The 'yield' keyword halts the function execution and sends a value back to the caller. It has an ability that it can resume the functionality from where it is left off.
syntax
function* generator(){ yeild 1; yeild 2; }
Example
In the following example, using a generator function, natural numbers 10,9 and 8 were printed. Instead of printing each number individually we can run a for loop and print whatever numbers we need.
<html> <body> <script> function * number() { var num = 10; while (true) { yield num--; } } var gen = number(); document.write(gen.next().value); document.write("</br>"); document.write(gen.next().value); document.write("</br>"); document.write(gen.next().value); </script> </body> </html>
Output
10 9 8
- Related Articles
- What are generator functions in JavaScript?
- Explain shorthand functions in JavaScript?
- Explain higher order functions in JavaScript.
- JavaScript Generator
- Explain asynchronous functions in JavaScript with an example
- Random color generator in JavaScript
- Random name generator function in JavaScript
- What are async generator methods in JavaScript?
- Regular functions vs Arrow functions in JavaScript?
- Explain important functions in math.h library functions using C language
- Explain ValueFromPipeline in PowerShell Advanced Functions.
- How to create a password generator - JavaScript?
- Arrow functions in Javascript
- Induction Generator (Asynchronous Generator)
- Explain C Error handling functions

Advertisements