Create an iterator with Java Scripts

An iterator is basically an object which can access items from it’s own collection one at a time. According to the Firefox website the object which can be used as an iterator must provides a method known as ‘next’ which can then be called by that object itself to iterate through a collection of items.

Basically what we need in our iterator object is two things, 1) The method which returns the next item 2) A boolean value which indicates whether we have reached the end of that iteration or not.

After I have read through the entire Firefox article I have came out with the below modified version from the iterators example on the Firefox website which I have omitted the boolean value in my code because the for loop will take care of everything and thus we can safely omit the boolean value. We also can name our method any name which we want, not necessary call it ‘next’, so I call it ‘again’. Below is the entire code…

function helloIterator(array) {
    var nextIndex = 0;
    
    return {
       again: function() {
           return {value: array[nextIndex++]};
       }
    };
}

var helloA = ['hello ', 'world', 'good', 'night!'];
var hello = helloIterator(helloA);

for(var i = 0; i < helloA.length; i++)
	console.log(hello.again().value);

The above code will result in the below outcome in the Firefox developer console.

hello
world 
good  
night! 

As you can see there is nothing so special about iterator which we can easily create one with any javascript object.

Like this post? Kindly share!