Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements