Iterables & Iterators

In JavaScript, iterables are objects that can be looped over with constructs like for...of. An iterator is an object that provides access to the elements of an iterable, one at a time, via a standardized method.

Illustration of Iterables & Iterators
Illustration of Iterables & Iterators

💡 What is an Iterable?

An object is iterable if it implements the Symbol.iterator method, which returns an iterator.

💡 What is an Iterator?

An iterator is an object with a next() method that returns an object with two properties: value (current element) and done (boolean indicating if iteration is complete).

Iterable vs Iterator
FeatureIterableIterator
Has Symbol.iteratorYesNo
Has next() methodNo (usually)Yes
Returns iteration objectYes (iterator)Returns {value, done}
ExamplesArray, Set, StringResult of calling [Symbol.iterator]()

Most built-in data structures like Array, String, Map, and Set are iterable.

📌 Deep Dive: Using an Iterator

JAVASCRIPT
const arr = ['a', 'b', 'c'];
const iterator = arr[Symbol.iterator]();

console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: 'c', done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Output
{ value: 'a', done: false }
{ value: 'b', done: false }
{ value: 'c', done: false }
{ value: undefined, done: true }

The for...of loop automatically uses the iterable's iterator:

📌 Deep Dive: Iterating with for...of

JAVASCRIPT
const str = 'Hi!';
for (const char of str) {
  console.log(char);
}
Output
H
i
!

⚠️ Important

Not all objects are iterable by default. Plain objects ({}) do not have a Symbol.iterator method and cannot be used in for...of loops without custom implementation.

You can create your own iterable by implementing [Symbol.iterator]:

📌 Deep Dive: Custom Iterable

JAVASCRIPT
const myIterable = {
  data: [10, 20, 30],
  [Symbol.iterator]() {
    let index = 0;
    const data = this.data;
    return {
      next() {
        if (index < data.length) {
          return { value: data[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

for (const num of myIterable) {
  console.log(num);
}
Output
10
20
30

💡 Key Takeaway

The iterator protocol standardizes how JavaScript accesses elements sequentially. Understanding iterables & iterators helps you work with custom and built-in data structures efficiently.