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