Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Compare a Generator to Using Array Map and Filter


    Generators offer flexible alternatives to working with arrays and how you want to iterate through the data. While most scenarios are covered by the methods included on Arrays such as "map" and "filter", generators are great for covering complex scenarios when writing all your logic in map and filter functions might become difficult.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    John Lindquist: 0:00 There are often times when you have a collection of data and you'll want to do something like have a result where the names filter out something like we only want the names that include a Y. Then after they include a Y we want to map that to something like name name, to lowercase. Then we can log out the result and have Mindy and Sally because Mindy and Sally have Ys and they're lower-cased.

    0:29 Generators can handle that same scenario, so I'm just going to call this a format function which can take an array. The logic here just looks like a for loop where you say let value of array.

    0:42 I can say if value includes Y then yield value to lower case. Then because this is an iterator we'll console log out an array where we spread the format of names. We get the exact same result over here.

    1:04 Because this is an iterator the benefits are things like you can yield whatever you want here. If you want to yield a spacer, let's save here. Then I can do spacer, spacer, Mindy, spacer, Sally. We could yield both the toLowerCase and the toUpperCase with no problem.

    1:25 We could yield the original array after each lower case value which gives you Mindy, then John, Mindy, Sally, Sally, John, Mindy, Sally. Or you could even return early after the first one.

    1:38 We'll just return here, hit save, and then we only get Mindy. This generator function is going to allow you to write many complex scenarios in a very common pattern which can be much easier to express than some of the functions you may have to write inside of filter and map functions.