THN Interview Prep

Iterator (Behavioral)

Intent / problem it solves

Provide sequential access to elements of an aggregate without exposing its internal representation. Decouple traversal algorithm from the collection.

When to use / when NOT

Use when collections hide storage details or when multiple traversal strategies exist.

Avoid when language iterators (for..of, Go range) already cover needs—still apply the idea of separate traversal.

Structure

Iterator interface (next, hasNext or range); aggregate exposes createIterator().

Loading diagram…

Go example

package main

import "fmt"

type Shelf struct {
	items []string
}

func (shelf *Shelf) Items() []string { return shelf.items }

type ShelfIterator struct {
	shelf *Shelf
	index int
}

func (iterator *ShelfIterator) Next() (string, bool) {
	if iterator.index >= len(iterator.shelf.items) {
		return "", false
	}
	value := iterator.shelf.items[iterator.index]
	iterator.index++
	return value, true
}

func main() {
	shelf := &Shelf{items: []string{"pen", "notebook"}}
	iterator := &ShelfIterator{shelf: shelf, index: 0}
	for {
		item, ok := iterator.Next()
		if !ok {
			break
		}
		fmt.Println(item)
	}
}

JavaScript example

class NumberRange {
  constructor(start, end) {
    this.start = start;
    this.end = end;
  }

  [Symbol.iterator]() {
    let current = this.start;
    const last = this.end;
    return {
      next() {
        if (current > last) {
          return { done: true };
        }
        const value = current;
        current += 1;
        return { value, done: false };
      },
    };
  }
}

const range = new NumberRange(2, 4);
console.log([...range]);

Interview phrase

“Iterator hides whether data lives in an array, linked list, or database page—callers just step forward without knowing storage.”

Link from LLD for custom collections, pagination cursors, or tree walks in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page