Answers for "iterators in javascript"

2

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
Posted by: Guest on May-12-2021
2

what is an iterator in javascript

The iterator is an object that returns values via its method next()
Posted by: Guest on July-02-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language