iterators in js 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()

Example 3: JavaScript — Generators

function* makeRangeIterator(start = 0, end = 100, step = 1) {
    let iterationCount = 0;
    for (let i = start; i < end; i += step) {
        iterationCount++;
        yield i;
    }
    return iterationCount;
}