# Iterator

> Traverse any collection — list, tree, graph, custom data structure — through a consistent interface without exposing how it's actually stored.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/iterator/

---

## Description
**Intent**: Give clients a uniform way to step through any collection regardless of its underlying storage structure.

**Context**: You have multiple collection types — arrays, linked lists, trees, database result sets — and client code that needs to traverse them all. Exposing internal structure forces clients to know too much and breaks when you change implementations.

**Solution**: Define an Iterator with `next()` and `hasNext()`. Each collection returns its own Iterator implementation. Client code uses the Iterator interface and never sees how the collection stores its data. Multiple iterators can traverse the same collection independently.


## Use Cases
Use when you want client code to traverse different collection types uniformly, or when you need multiple simultaneous traversals of the same collection.



## Implementation Example

```javascript
class AlphabeticalIterator {
  constructor(collection) {
    this.collection = collection;
    this.position = 0;
  }
  next() {
    const item = this.collection.getItems()[this.position];
    this.position += 1;
    return item;
  }
  hasNext() {
    return this.position < this.collection.getCount();
  }
}

```



## Trade-offs


### Advantages

- Client code is agnostic to how the collection stores its data.

- Multiple iterators can traverse the same collection independently and simultaneously.




### Considerations & Drawbacks

- Pure overhead for simple arrays or collections that are already easily traversable.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/iterator)

