back to series

Implement an array iterator

Iterator in Javascript is an object which defines a sequence and potentially a return value upon its termination.

Technically, iterators are objects which follows the iterator protocol and by having a next() method that returns an object with two properties:

  1. value : The next value in the iteration sequence.
  2. done : This is true if the last value in the sequence has already been consumed, else false.

You can learn more about iterators on MDN.

However, for our use case, we have to implement a iteratorArray method, which takes an array as argument and returns an object with next() and done() properties.

Calling the next() method should return the next item in array until the end of array, after which it returns null and done() methods returns a boolean flag denoting if all iterations are completed.

Variation: Basic implementation

1. Basic Implementation

./src/array-iterator.js
function arrayIterator(arr) {
let activeIndex = 0;
return {
done() {
if (activeIndex < arr.length) {
return false;
}
return true;
},
next() {
if (activeIndex < arr.length) {
let res = arr[activeIndex];
activeIndex++;
return res;
} else {
return null;
}
}
};
}
// Usage of the arrayIterator
const iterator = arrayIterator([1, 2, 3]);
console.log(iterator.next()); //1
console.log(iterator.done()); // false
console.log(iterator.next()); //2
console.log(iterator.next()); // 3
console.log(iterator.done()); // true
console.log(iterator.next()); // null
console.log(iterator.done()); // true
Variation: With startIndex

2. With startIndex implementation

A startIndex value can be passed, and iteration should start from that index.

./src/array-iterator.js
function arrayIterator(arr, startIndex = 0) {
let activeIndex = startIndex;
return {
done() {
if (activeIndex < arr.length) {
return false;
}
return true;
},
next() {
if (activeIndex < arr.length) {
let res = arr[activeIndex];
activeIndex++;
return res;
} else {
return null;
}
}
};
}
const iterator = arrayIterator([1, 2, 3], 1);
console.log(iterator.next()); //2
console.log(iterator.done()); // false
console.log(iterator.next()); //3
console.log(iterator.done()); // true
console.log(iterator.next()); // null
console.log(iterator.done()); // true

Further Reading

I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.

By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.

Wishing you best. Happy Interviewing 🫡.