फ़ंक्शन* डिक्लेरेशन का उपयोग जेनरेटर फंक्शन को परिभाषित करने के लिए किया जाता है। यह जेनरेटर ऑब्जेक्ट देता है। जब कोई फ़ंक्शन बाहर निकलता है और बाद में फिर से शुरू होता है तो जेनरेटर फ़ंक्शंस बीच में कोड के निष्पादन की अनुमति देता है। इसलिए, जनरेटर का उपयोग एक कोड में प्रवाह नियंत्रण को प्रबंधित करने के लिए किया जा सकता है।
सिंटैक्स
यहां सिंटैक्स है -
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {} आइए देखें कि जनरेटर फ़ंक्शन का उपयोग कैसे करें
उदाहरण
लाइव डेमो
<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>