{"id":7069,"date":"2020-05-15T19:31:20","date_gmt":"2020-05-15T14:01:20","guid":{"rendered":"https:\/\/code4developers.com\/?p=7069"},"modified":"2020-05-15T19:32:19","modified_gmt":"2020-05-15T14:02:19","slug":"ways-to-use-generator-functions-in-javascript","status":"publish","type":"post","link":"https:\/\/code4developers.com\/ways-to-use-generator-functions-in-javascript\/","title":{"rendered":"Ways to use Generator Functions in JavaScript"},"content":{"rendered":"<p>In this Article we will see below points<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>Generator Functions<\/li>\n<li>Recap: Functions<\/li>\n<li>How does it work?<\/li>\n<li>4 ways to use Generator Functions with Examples<\/li>\n<li>Advantages of using Generator function<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><!--more--><\/p>\n<h3 id=\"what-is-gf-now\"><span id=\"what-are-generator-functions\">What are Generator Functions?<\/span><\/h3>\n<p><em>Ever imagined what would happen if a function had an infinite input or output to deal with? That is exactly what you can handle with Generator functions.<\/em><\/p>\n<p>A Generator function returns us an iterator, which can be used to stop the function in the middle, do something, and then resume it whenever. A normal function starts executing and returns when the function completes, but a Generator function can be stopped any number of times and resumed later.<\/p>\n<h3 id=\"function\"><span id=\"what-is-a-function\">What is a Function?<\/span><\/h3>\n<p>A function is a block of code that can be called any number of times to get the functionality done and sometimes the result returned.<\/p>\n<h3 id=\"how-it-works\"><span id=\"how-does-it-work\">How does it Work?<\/span><\/h3>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>Calling a Generator function does not execute the function completely as soon as its called. It will return an\u00a0<strong>iterator<\/strong>\u00a0object that can be used to use the function.<\/li>\n<li>So this function can be executed part by part, where these parts are decided by the <code>yield<\/code>\u00a0expression. ( Code explanation below, don&#8217;t worry ).<\/li>\n<li>To execute these parts, the\u00a0<code>.next()<\/code> method is used on the iterator. When the <code>.next()<\/code>\u00a0method is called, the function resumes execution until the next\u00a0<code>yield<\/code> is found, or the function completes or a <code>return<\/code>\u00a0statement is executed.<\/li>\n<li>Everytime you execute the\u00a0<code>.next()<\/code>\u00a0method, the generator function returns you with an object that looks like this<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<pre class=\"theme:shell-default lang:js decode:true\">{\r\n   value: 'some-value',\r\n   done: false\r\n}<\/pre>\n<p>The\u00a0<code>value<\/code>\u00a0here is the value sent by the\u00a0<code>yield<\/code>\u00a0and the\u00a0<code>done<\/code>indicates if the generator function has run completely.<\/p>\n<h3 id=\"examples\">Examples<\/h3>\n<p><strong>1. Basic usage of Generator Function<\/strong><\/p>\n<p>Generator functions are defined using the\u00a0<code>*<\/code>\u00a0asterisk either immediately after the function keyword or right before the function name. The below example creates an infinite number of natural numbers, which can be used when needed.<\/p>\n<pre class=\"theme:shell-default lang:js decode:true\">   function *naturalNumbers() {\r\n        let number=1;\r\n        while (true)\r\n            yield number++;\r\n    }\r\n\r\n    var naturalNumberIterator = naturalNumbers();\r\n\r\n    console.log(naturalNumberIterator.next().value);\r\n    console.log(naturalNumberIterator.next().value);\r\n    console.log(naturalNumberIterator.next().value);\r\n    console.log(naturalNumberIterator.next().value);<\/pre>\n<p>The output for the above code:<\/p>\n<pre class=\"theme:shell-default lang:js decode:true \">1\r\n2\r\n3\r\n4<\/pre>\n<p><strong>2. Calling Generator within a Generator (wooo&#8230; inception)<\/strong><\/p>\n<p>We can use the\u00a0<code>yield*<\/code>\u00a0to call another generator from within a generator.\u00a0<em>( Crazy right? )<\/em><\/p>\n<pre class=\"theme:shell-default lang:default decode:true \">   function *anotherGenerator(name) {\r\n        yield `From Another Generator, ${name}`\r\n    }\r\n\r\n    function *myGenerator(name) {\r\n        yield `Hi ${name}`;\r\n        yield* anotherGenerator(name)\r\n        yield 'Bye!'\r\n    }\r\n\r\n    let gen = myGenerator('arif')\r\n    console.log(gen.next().value);\r\n    console.log(gen.next().value);\r\n    console.log(gen.next().value);<\/pre>\n<p>The output for the above code:<\/p>\n<pre class=\"lang:default decode:true \">Hi arif\r\nFrom Another Generator, arif\r\nBye!<\/pre>\n<p><strong>3. Passing arguments into Generators<\/strong><\/p>\n<p>Wonder what else the Generators could do? What if I told you that you can pass arguments into Generators? Again, just pass the parameters in the\u00a0<code>.next()<\/code>\u00a0and use it in the\u00a0<code>yield<\/code>\u00a0keyword inside the Generator function. Below is a demonstrated example of it.<\/p>\n<pre class=\"theme:shell-default lang:js decode:true \">   function *myGenerator() {\r\n        console.log('Hey ', yield)\r\n        console.log('Are you ',yield)\r\n    }\r\n\r\n    let gen = myGenerator()\r\n\r\n    gen.next()\r\n    gen.next('arif')\r\n    gen.next('arif khoja')<\/pre>\n<p>Note that, you have to call\u00a0<code>.next()<\/code>\u00a0method once in the beginning, which will execute the function until the yield keyword. The next\u00a0<code>.next('tharun')<\/code>\u00a0will send the\u00a0<code>'tharun'<\/code>\u00a0to the Generator and is replaced in place of yield. Below is the output of the program.<\/p>\n<pre class=\"theme:shell-default lang:js decode:true \">Hey arif\r\nAre you arif khoja<\/pre>\n<p><strong>4. Once returned, no more yields<\/strong><\/p>\n<p>Wonder what would happen if you execute a\u00a0<code>return<\/code>\u00a0statement inside a generator? Well, I have demonstrated just that in the below example. It returns from the generator function without providing access to any of the\u00a0<code>yield<\/code>\u00a0below.<\/p>\n<pre class=\"theme:shell-default lang:js decode:true \"> function *yieldAndReturn() {\r\n    yield \"U\";\r\n    return \"R\";\r\n    yield \"unreachable\";\r\n   }\r\n\r\n    var gen = yieldAndReturn()\r\n    console.log(gen.next());\r\n    console.log(gen.next());\r\n    console.log(gen.next());<\/pre>\n<p>The output is given below. You cannot\u00a0<code>yield<\/code>\u00a0the &#8220;unreachable&#8221;.<\/p>\n<pre class=\"theme:shell-default lang:js decode:true\">{\"value\":\"U\",\"done\":false}\r\n{\"value\":\"R\",\"done\":true}\r\n{\"done\":true}<\/pre>\n<h3 id=\"pros\"><span id=\"advantages-of-using-generators-why-should-you-use-them\">Advantages of using Generators? Why Should you use them?<\/span><\/h3>\n<p><strong>1. Lazy Evaluation &#8211; Run only when you need<\/strong><\/p>\n<p>Say there is an Infinite Stream of data, we cannot spend our whole life evaluating that data. Hence we can use Generator function to evaluate as and when required.<\/p>\n<p><strong>2. Memory Efficient<\/strong><\/p>\n<p>As the Lazy Evaluation method is used, only those data and those computations that are necessary, are used.<\/p>\n<p>&nbsp;<\/p>\n<p>Hope you had a good read if you liked the article give a like or drop a message and if you want to learn more advanced stuff you can also read <a href=\"https:\/\/code4developers.com\/functional-programming-currying\/\" target=\"_blank\" rel=\"noopener noreferrer\">Functional Programming in Javascript \u2013 Currying<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this Article we will see below points Generator Functions Recap: Functions How does it work? 4 ways to use Generator Functions with Examples Advantages of using Generator function<\/p>\n","protected":false},"author":7,"featured_media":6799,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[2],"tags":[323,322,22,312],"powerkit_post_featured":[],"class_list":{"0":"post-7069","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"tag-advanced-javascript","9":"tag-generator-functions","10":"tag-javascript","11":"tag-javascript-functions"},"jetpack_featured_media_url":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2020\/04\/avatar-js.png?fit=512%2C512&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8NAi4-1Q1","jetpack-related-posts":[{"id":3311,"url":"https:\/\/code4developers.com\/default-parameter-in-a-javascript-function\/","url_meta":{"origin":7069,"position":0},"title":"Default Parameter in JavaScript function","author":"Yatendrasinh Joddha","date":"March 17, 2018","format":false,"excerpt":"In any programming language we often require having default parameter or default value for the parameter in a function. JavaScript allow us to initialize parameter a default value. If you are not passing any value to the parameter, then the default value of the parameter will be undefined. Let's consider\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":3230,"url":"https:\/\/code4developers.com\/whats-new-ecmascript-2018\/","url_meta":{"origin":7069,"position":1},"title":"What\u2019s new in ECMAScript 2018","author":"Arif Khoja","date":"February 16, 2018","format":false,"excerpt":"Four new feature proposals for the specification underlying JavaScript are finalized and four others are under consideration ECMAScript, the standard specification underlying JavaScript, is on track for a new release, likely in June. So far, four proposals have been finalized for inclusion in the ECMAScript 2018 specification, said Zibi Braniecki,\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"ecma script","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/ecma.png?fit=400%2C277&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":3318,"url":"https:\/\/code4developers.com\/arguments-object-javascript-function\/","url_meta":{"origin":7069,"position":2},"title":"arguments object in JavaScript function","author":"Yatendrasinh Joddha","date":"March 19, 2018","format":false,"excerpt":"The arguments object is an Array-like object matching to the arguments passed to a function. The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function's arguments within the function by using the arguments object.Let's consider below code: function addition(num1, num2) { return\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":2610,"url":"https:\/\/code4developers.com\/semicolon-in-javascript\/","url_meta":{"origin":7069,"position":3},"title":"Importance of Semicolon [;] In JavaScript","author":"Yatendrasinh Joddha","date":"June 19, 2017","format":false,"excerpt":"It is said that in JavaScript semicolons are not compulsory. It's true, because JavaScript automatically inserts a semicolons at required place and it is know as \"Automatic Semicolon Insertion\". This behavior of JavaScript confuses us a lot. This article is written for those who have just started writing JavaScript and\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":14692,"url":"https:\/\/code4developers.com\/demystifying-javascript-tree-shaking\/","url_meta":{"origin":7069,"position":4},"title":"Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size","author":"Yatendrasinh Joddha","date":"October 17, 2023","format":false,"excerpt":"In the ever-evolving world of web development, optimizing the performance of your JavaScript applications is a key concern. One effective technique to achieve this is called \"tree shaking.\" In this article, we'll delve into the concept of tree shaking, explain how it works, and provide a detailed example to illustrate\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":3321,"url":"https:\/\/code4developers.com\/spread-syntax-in-javascript\/","url_meta":{"origin":7069,"position":5},"title":"Spread syntax (three dots) in JavaScript","author":"Yatendrasinh Joddha","date":"March 21, 2018","format":false,"excerpt":"Spread syntax which is used by typing three dots (...) in JavaScript. It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls\u00a0or elements for array are expected. It can also be used for an\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/7069","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/comments?post=7069"}],"version-history":[{"count":4,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/7069\/revisions"}],"predecessor-version":[{"id":7076,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/7069\/revisions\/7076"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media\/6799"}],"wp:attachment":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media?parent=7069"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/categories?post=7069"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/tags?post=7069"},{"taxonomy":"powerkit_post_featured","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/powerkit_post_featured?post=7069"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}