1

I read the javascript new features Iterator and Generator here but i didn't get in which scenario we should use Iterator over Generator. Also what is the main difference in between these two.

1
  • The descriptions in that link are quite clear - use the right tool for the the job, i.e. use a hammer on a nail and a screwdriver on a screw Commented Jul 18, 2017 at 6:09

1 Answer 1

1

An Iterator allows you to encapsulate traversal. So given one item, you can get to the next item. For example, if you had a blindfold on and you had a row of people and each person was holding the shirt of the person in front of them, you could traverse the queue of people by following their hands. In this example, you would be the Iterator keeping track of who you were touching and the people would be the Iterables.

I think of a generator as a state machine with each yield as a state transition. So for example, if you had the following generator function

function* idMaker() {
  var index = 0;
  while(true)
    yield index++;
}

If would jump from the state 1 -> 2 -> 3 etc. Intuitively, you can think about each state as being a person in a queue and each time you yield, you are following the hands of the person grabbing on the back of the shirt of the next person to get the next state.

Now here's where it gets more confusing. Generator objects are both Iterators and Iterables. You can call generator.next() on a generator object to get the next yielded value as well as calling generator[Symbol.iterator] to get an iterator object which will have its own next() function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.