Skip to the content

Your own iterable

JavaScript · Unit 16: Iterators and generators

An object of yours can't be looped over because it's missing the method that hands over the values. That method has a fixed name: [Symbol.iterator], brackets included.

Write it as a generator, with the asterisk in front, and your class works in a for...of.

class Line {
  constructor(people) {
    this.people = people;
  }
  *[Symbol.iterator]() {
    for (const p of this.people) {
      yield p;
    }
  }
}
const f = new Line(["Ann", "Leo"]);
for (const p of f) {
  console.log(p);
}

Prints

Ann
Leo

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blanks so the class can be looped over with a for...of.

  3. 3. Find the bug

    It should print the two names in the line, one per row. Which line has the bug?

  4. 4. Predict the output

    The class hands over only the passing grades, 6 and up.

  5. 5. Multiple choice

    With this object, what happens if you write for (const c of box)?

  6. 6. Predict the output

    What does this code print?

  7. 7. Put the lines in order

    Build the Week class so that [...new Week()] gives its two days.

  8. 8. Multiple choice

    What does an object of yours need before it can be used in a for...of?

  9. 9. Complete the code

    Fill in the blank to count how many different letters the object hands over.

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →