Skip to main content

Iterator Pattern in JavaScript (Live Playground)

The Iterator pattern is a behavioral design pattern that provides a standardized way to traverse a collection of items without exposing the underlying implementation. This pattern allows you to create a consistent interface for different types of collections. In this tutorial, we'll explore the Iterator pattern in JavaScript, including its use cases, implementation, and benefits.

Why Use the Iterator Pattern?

The Iterator pattern is useful when you want to:

  1. Provide a consistent way to traverse different types of collections.
  2. Decouple the traversal logic from the collection itself.
  3. Enable multiple traversal operations on the same collection simultaneously.

Implementing the Iterator Pattern in JavaScript

Here's an example of how to implement the Iterator pattern using JavaScript classes:

// Iterator interface
class Iterator {
hasNext() {}
next() {}

// Concrete iterator
class ArrayIterator extends Iterator {
constructor(collection) {
this.collection = collection;
this.index = 0;

hasNext() {
return this.index < this.collection.length;

next() {
const result = this.collection[this.index];
return result;

// Collection interface
class Collection {
createIterator() {}

// Concrete collection
class ArrayCollection extends Collection {
constructor() {
this.items = [];

addItem(item) {

createIterator() {
return new ArrayIterator(this.items);

// Client code
const collection = new ArrayCollection();

const iterator = collection.createIterator();

while (iterator.hasNext()) {
console.log(; // Output: 1, 2, 3

In this example, the Iterator class represents the iterator interface, and ArrayIterator is a concrete iterator class. The Collection class represents the collection interface, and ArrayCollection is a concrete collection class. The client code creates a collection, adds items, and traverses the collection using the iterator.

Live Playground, Try it Yourself

Benefits of the Iterator Pattern

Implementing the Iterator pattern in your JavaScript projects offers several benefits:

  1. Consistency: The Iterator pattern provides a consistent way to traverse different types of collections, making your code more robust and easier to maintain.
  2. Decoupling: The Iterator pattern decouples the traversal logic from the collection itself, promoting separation of concerns and allowing you to easily add or modify traversal algorithms.
  3. Concurrency: The Iterator pattern enables multiple traversal operations on the same collection simultaneously, improving performance and usability.


In summary, the Iterator pattern is a valuable tool in JavaScript development that can help you create maintainable, scalable code. By understanding and implementing this pattern, you can enhance your web development skills and create more robust applications.