Labs ICT
Pro Login

Iterators

1 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

The Iterator Protocol

An object is iterable if it implements Symbol.iterator. The method must return an object with a next() method yielding { value, done }.

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

for (const num of range) {
  console.log(num);
}

Custom Iterables

Create iterable objects representing any sequence — like Fibonacci numbers, custom collections, or infinite sequences.

const fibonacci = {
  [Symbol.iterator]() {
    let a = 0, b = 1;
    return {
      next() {
        const value = a;
        a = b;
        b = value + b;
        if (value > 50) return { done: true };
        return { value, done: false };
      }
    };
  }
};

for (const num of fibonacci) {
  console.log(num);
}

Built-in Iterables

Arrays, Strings, Maps, Sets, and NodeLists are built-in iterables. You can use for...of on all of them.

const str = "Hello";
for (const char of str) {
  console.log(char);
}

const map = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of map) {
  console.log(key + ":", value);
}