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.
-
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 screwJaromanda X– Jaromanda X2017-07-18 06:09:27 +00:00Commented Jul 18, 2017 at 6:09
1 Answer
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.