• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • JavaScript

Ways to use Generator Functions in JavaScript

  • Arif Khoja
  • May 15, 2020
  • 3 minute read
Functional-programming-js
Total
0
Shares
0
0
0

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

What are Generator Functions?

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.

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.

What is a Function?

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.

How does it Work?

    1. Calling a Generator function does not execute the function completely as soon as its called. It will return an iterator object that can be used to use the function.
    2. So this function can be executed part by part, where these parts are decided by the yield expression. ( Code explanation below, don’t worry ).
    3. To execute these parts, the .next() method is used on the iterator. When the .next() method is called, the function resumes execution until the next yield is found, or the function completes or a return statement is executed.
    4. Everytime you execute the .next() method, the generator function returns you with an object that looks like this
{
   value: 'some-value',
   done: false
}

The value here is the value sent by the yield and the doneindicates if the generator function has run completely.

Examples

1. Basic usage of Generator Function

Generator functions are defined using the * asterisk 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.

   function *naturalNumbers() {
        let number=1;
        while (true)
            yield number++;
    }

    var naturalNumberIterator = naturalNumbers();

    console.log(naturalNumberIterator.next().value);
    console.log(naturalNumberIterator.next().value);
    console.log(naturalNumberIterator.next().value);
    console.log(naturalNumberIterator.next().value);

The output for the above code:

1
2
3
4

2. Calling Generator within a Generator (wooo… inception)

We can use the yield* to call another generator from within a generator. ( Crazy right? )

   function *anotherGenerator(name) {
        yield `From Another Generator, ${name}`
    }

    function *myGenerator(name) {
        yield `Hi ${name}`;
        yield* anotherGenerator(name)
        yield 'Bye!'
    }

    let gen = myGenerator('arif')
    console.log(gen.next().value);
    console.log(gen.next().value);
    console.log(gen.next().value);

The output for the above code:

Hi arif
From Another Generator, arif
Bye!

3. Passing arguments into Generators

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 .next() and use it in the yield keyword inside the Generator function. Below is a demonstrated example of it.

   function *myGenerator() {
        console.log('Hey ', yield)
        console.log('Are you ',yield)
    }

    let gen = myGenerator()

    gen.next()
    gen.next('arif')
    gen.next('arif khoja')

Note that, you have to call .next() method once in the beginning, which will execute the function until the yield keyword. The next .next('tharun') will send the 'tharun' to the Generator and is replaced in place of yield. Below is the output of the program.

Hey arif
Are you arif khoja

4. Once returned, no more yields

Wonder what would happen if you execute a return statement 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 yield below.

 function *yieldAndReturn() {
    yield "U";
    return "R";
    yield "unreachable";
   }

    var gen = yieldAndReturn()
    console.log(gen.next());
    console.log(gen.next());
    console.log(gen.next());

The output is given below. You cannot yield the “unreachable”.

{"value":"U","done":false}
{"value":"R","done":true}
{"done":true}

Advantages of using Generators? Why Should you use them?

1. Lazy Evaluation – Run only when you need

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.

2. Memory Efficient

As the Lazy Evaluation method is used, only those data and those computations that are necessary, are used.

 

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 Functional Programming in Javascript – Currying

Arif Khoja
Arif Khoja

Arif Khoja is a Developer. He is a Javascript Enthusiatic who loves logical programming and has first hand experience in building a cutting edge internet product using Angular. He is also an open source freak and keen about learning and sharing. He writes Javascript both frontend and backend. He loves learning and sharing tech all the time. He also has a hands on experience in SEO and writes articles about latest emerging technologies.

Views: 2,184

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    1 year ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    2 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
  • New Learning Models for Fall 2020

    New Learning Models for Fall 2020

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

%d