javascript iterator code example
Example 1: iterators in javascript
function fruitsIterator(array) {
let nextIndex = 0;
return {
next: function () {
if (nextIndex < array.length) {
return {
value: array[nextIndex++],
done: false,
};
} else {
return { done: true };
}
},
};
}
let myArr = ["apple", "banana", "orange", "grapes"];
console.log("My array is", myArr);
const fruits=fruitsIterator(myArr);
console.log(fruits.next());
console.log(fruits.next());
console.log(fruits.next());
Example 2: what is an iterator in javascript
The iterator is an object that returns values via its method next()