💻 Programming

Iterator

Iterator

An object that traverses the elements of a collection. The basis of the for loop.

📖 Detailed Explanation

An Iterator is an object that lets you access the elements of a collection one at a time, in sequence. It allows you to traverse elements in a consistent way without knowing the internal implementation of various data structures such as arrays, Sets, and Maps, and it is the core of the design pattern that separates data structures from algorithms.

In JavaScript, an iterator is an object with a `next()` method that returns a result of the form `{ value, done }` on each call. value is the current element's value, and done is a boolean indicating whether the traversal has finished. Objects that follow this protocol can be used automatically in `for...of` loops.

In Python, iterators are implemented with the `__iter__()` and `__next__()` magic methods. In Java, the `hasNext()` and `next()` methods of the `Iterator` interface are used. The syntax differs by language, but the core concept of "return the current element + move to the next" is the same.

In practice, iterators are used for processing large amounts of data, lazy evaluation, and generating infinite sequences. Combined with generators, they let you build memory-efficient data pipelines, which is especially useful for stream processing and implementing pagination.

💻 Code Example

// 1. 기본 이터레이터 사용법
const numbers = [10, 20, 30];
const iterator = numbers[Symbol.iterator]();

console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next()); // { value: 20, done: false }
console.log(iterator.next()); // { value: 30, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

// 2. for...of 루프 (내부적으로 이터레이터 사용)
const fruits = ['사과', '바나나', '딸기'];
for (const fruit of fruits) {
    console.log(fruit); // 사과, 바나나, 딸기 순서대로 출력
}

// 3. 커스텀 이터레이터 구현 - Range 객체
class Range {
    constructor(start, end, step = 1) {
        this.start = start;
        this.end = end;
        this.step = step;
    }

    [Symbol.iterator]() {
        let current = this.start;
        const end = this.end;
        const step = this.step;

        return {
            next() {
                if (current <= end) {
                    const value = current;
                    current += step;
                    return { value, done: false };
                }
                return { value: undefined, done: true };
            }
        };
    }
}

// 사용 예시
const range = new Range(1, 5);
console.log([...range]); // [1, 2, 3, 4, 5]

for (const num of new Range(0, 10, 2)) {
    console.log(num); // 0, 2, 4, 6, 8, 10
}

// 4. 제너레이터로 이터레이터 쉽게 만들기
function* fibonacci(limit) {
    let [prev, curr] = [0, 1];
    while (curr <= limit) {
        yield curr;
        [prev, curr] = [curr, prev + curr];
    }
}

console.log([...fibonacci(100)]);
// [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

// 5. Map과 Set의 이터레이터
const userMap = new Map([
    ['alice', { age: 25 }],
    ['bob', { age: 30 }]
]);

for (const [name, info] of userMap) {
    console.log(`${name}: ${info.age}세`);
}

🗣️ Say It Like This in Practice

💬 In a Meeting
"When processing a large CSV file, loading the whole thing into memory causes an OOM. If you read and process it one line at a time with the iterator pattern, you can keep memory usage constant."
💬 In an Interview
"JavaScript's iterable protocol just requires implementing the Symbol.iterator method. If this method returns an iterator object with next(), it can be traversed automatically with for...of or the spread operator."
💬 In a code review
"Use for...of instead of for...in here. for...in iterates over an object's enumerable properties, while for...of iterates over an iterable's values. Using for...in on an array yields indexes as strings, which can cause bugs."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Iterators are single-use

Once an iterator has been traversed, it cannot be reused. To traverse again, you must create a new iterator. Spreading an exhausted iterator again with `[...iterator]` gives an empty array.

❌
Confusing for...in and for...of

`for...in` iterates over an object's keys (property names), while `for...of` iterates over an iterable's values. Using `for...in` on an array returns indexes as strings, which can cause unintended bugs.

✅
Implement simply with generators

Rather than implementing a custom iterator by hand, using a generator function (function*) lets you create an iterator much more concisely with the yield keyword. State management is also handled automatically.

🔗 Related Terms

📚 Learn More