Become a member
to unlock all features

Level Up!

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


    Avoid Nested For Loops with Generators


    Generators allow you to hook together multiple generators with the yield* syntax. This allows you to branch off into many different types of iterations within the main iteration and covers complex scenarios where you usually end up reaching for nested for loops.



    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




    Instructor: 0:00 Now because generators give us iterables and yield* can yield iterables, we can also create a second generator and yield those from another generator. For example, if I call this a shoutIterator, this can be a function, and this can take a word. Then we'll just go ahead and yield the word plus !.

    0:27 Now inside of my reverseIterator, I can yield* my shoutIterator, and we'll just pass in "hello." You'll see hello with an exclamation point. I could shout progressively louder, so 2, 3, and I can get hello and then louder, and louder, or I could combine data from my array, say something like array , then yield out array, array.

    0:55 I could do things like a with one exclamation point, louder and louder, B, and C, all because a generator gives us an iterable which a yield can loop through itself.

    1:07 You're probably thinking if you would do this traditionally you would have done nested for loops or a solution like that. Whereas with generators, you get a very easy-to-follow syntax which is very obvious what it's doing, and rather than nested for loops you're just using a function inside of a function, which is a very common and natural pattern.