InterviewHubPRO
Section Overview
Q239

Question 239 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

46%
JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

What is an Iterator

An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a next() method which returns an object with two properties: value (the next value in the sequence) and done (which is true if the last value in the sequence has been consumed).

Practical Code Example

javascript
// Iterator Protocol: Object with a next() method returning { value, done }
function makeIterator(array) {
  let nextIndex = 0;
  return {
    next: function() {
      return nextIndex < array.length
        ? { value: array[nextIndex++], done: false }
        : { value: undefined, done: true };
    }
  };
}
const it = makeIterator(['A', 'B']);
console.log(it.next()); // { value: 'A', done: false }
console.log(it.next()); // { value: 'B', done: false }
console.log(it.next()); // { value: undefined, done: true }