Array iterator method in JavaScript

Create an iterator method that accepts an array and returns a new method, that will return the next array value on each invocation.

Example

let iterator = helper([1, 2, "hello"]);
console.log(iterator.next()); // 1
console.log(iterator.next()); // 2
console.log(iterator.done()); // false
console.log(iterator.next()); // "hello"
console.log(iterator.done()); // true
console.log(iterator.next()); // "null"

We can create this helper function by forming a closure and returning an object with two methods next and done.

Create a index tracker in the outer function that will help to return the next value from the next() method.

In the done() return boolean flag depending upon the index position on the input array’s size.

const helper = (array) => {
  // track the index
  let nextIndex = 0;
  
  // return two methods
  return {
    // return the next value
    // or null
    next: function () {
      return nextIndex < array.length
        ? array[nextIndex++]    
        : null;
    },
    
    // returns boolean value
    // if all the values are returned from array
    done: function () {
      return nextIndex >= array.length;
    }
  };
};
let iterator = helper([1, 2, "hello"]);
console.log(iterator.next()); // 1
console.log(iterator.next()); // 2
console.log(iterator.done()); // false
console.log(iterator.next()); // "hello"
console.log(iterator.done()); // true
console.log(iterator.next()); // "null"