I’m not going to lie, this episode of Programming By Stealth with Bart Busschots was a bit head bendy. Bart explains JavaScript Iterator Objects and Generator functions but without his excellent examples I’m certain I would never have been able to get the concepts to even slightly congeal in my brain. Iterator Objects and Generator functions are some of the joys of ES6 and have great value.
That value is demonstrated in the succinctness of the code Bart writes for us to create a Fibonacci series in a beautiful web form. That work, by the way, is a bonus challenge if you’re done with your homework from the previous episodes. As you listen along, if you hear us yelling “spoiler alert” and making alarming noises, that’s when Bart’s solution to the challenge is about to be described. It’s a rare instance where I actually let you have one chapter mark in Programming By Stealth so you’ll be able to jump back to the solution after you’re done with your own solution.
Bart’s tutorial shownotes can be found at pbs.bartificer.net/…
I was also wondering why the Iterator.next() function would return value AND done when it seemed like an “undefined” value by itself would do — or marking the last one as done: true would.
But if you set up your array like this:
const myArray = [‘first’,’second’,,’4th’]
then the third iteration would be:
{value: undefined, done: false}
That eliminates having value: “undefined” be the finishing determinator, as one more next() will return:
{value: “4th”, done: false}
If the blank (undefined) third object in the list were the last one and we returned:
{value: undefined, done: true}
because it was the last, then how would we distinguish it from the there being no more items in the Array, since that will continue to be the return value for next() thereafter.
When Bart first mentioned that there were the two properties to the return value, it seemed like a bit of a waste. But after considering the fringe case of having undefined objects in the list, it makes sense.
I’m just getting into JavaScript again after years away from it and it has changed a LOT in the past several years. Looking at a lot of the StackOverflow answers up until listening to Bart’s recent review sessions was confusing at best. Now I’m loving what they’ve done to the language with ES6.