javascript iterator code example

Example 1: iterators in javascript

//Iterators
function fruitsIterator(array) {
  let nextIndex = 0;
  //fruitsIterator will return an object
  return {
    next: function () {
      if (nextIndex < array.length) {
        //next function will return the below object
        return {
          value: array[nextIndex++],
          done: false,
        };
      } else {
        return { done: true };
      }
    },
  };
}
let myArr = ["apple", "banana", "orange", "grapes"];
console.log("My array is", myArr);

//using the iterator 
const fruits=fruitsIterator(myArr);
console.log(fruits.next()); //apple
console.log(fruits.next());//banana
console.log(fruits.next());//grapes

Example 2: what is an iterator in javascript

The iterator is an object that returns values via its method next()