Iterator Pattern

const items = [1, "a", 3, "test"];

function ItemIterator(items) {
  this.items = items;
  this.length = items.length - 1;
  this.index = 0;
}

ItemIterator.prototype = {
  [Symbol.iterator]() {
    return this;
  },
  hasNext: function () {
    return this.index <= this.length;
  },
  next: function () {
    if (this.index <= this.length) {
      return { value: this.items[this.index++], done: false };
    } else {
      return { done: true };
    }
  },
};

const values = new ItemIterator(items);

for (let value of values) {
  console.log(value);
}
// 1 a 3 test

Using ES5 syntax

const items = [1, "a", 3, "test"];

class ItemIterator {
  constructor(items) {
    this.items = items;
    this.length = items.length - 1;
    this.index = 0;
  }
  [Symbol.iterator]() {
    return this;
  }
  hasNext() {
    return this.index <= this.length;
  }
  next() {
    if (this.index <= this.length) {
      return { value: this.items[this.index++], done: false };
    } else {
      return { done: true };
    }
  }
}

const values = new ItemIterator(items);

for (let value of values) {
  console.log(value);
}
// 1 a 3 test