Become a member
to unlock all features

Level Up!

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


    Create Your First Iterator in JavaScript


    Iterators are the foundation of generators. Much of the misunderstanding around generators comes from the lack of understanding iterators. An iterator has a Symbol.iterator property with an object that contains a next method which defines what is output each iteration.



    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: To create our own iterator we're going to take apart the pieces of this for loop and use them to create an iterator. First we have some logic of a value of increments and how it starts, so we'll bring that out, paste that here. Then we have when it ends and what happens each time it iterates through the loop.

    We're going to wrap these two things inside of a function called next. We'll call this function next here. Next returns an object that has a value and that value is going to be this piece here, i++. It's going to increment this i up here every time this function is called.

    An ending point where a done, we'll take this and we'll call this done. Although for our use case we need to flip this, otherwise it starts out at done because 0is less than 10. We want this to be true when i is greater than 10.

    We can just call this function. We could say console log next. You'll see value 0done false. We can do that a whole bunch of times until it gets beyond 10. You'll see once we get to 10 it becomes true. Everything before that is 1 through 10 and false. That's essentially how the iterator works, but to make it work inside of a for loop we need to create an object.

    We'll call this an iterator or an iterable. On that object just like on an array you need a symbol iterator key or technically a computed property. This is a function which returns an object with next on it. Now with that iterator we can say for let value of iterator. Then just log out all the values of the iterator. Save there, we get 0through 9. Once done is true it stops.