×

javascript · level 3 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

for...of asks an for one value at a time.

Arrays and strings are : for...of can walk through them. Behind the scenes it asks for an iterator, an object whose next() method returns { value, done }. The loop keeps calling next() until done is true.

The method that makes the iterator lives under a special key, . Give your own object that method, and for...of and spread both work with it, as if it were an array.

const countdown = {
  [Symbol.iterator]() {
    let current = 3;
    return {
      next() {
        if (current === 0) { return { value: undefined, done: true }; }
        current--;
        return { value: current + 1, done: false };
      }
    };
  }
};
for (const n of countdown) { console.log(n); }
console.log([...countdown]);

Square brackets around a key, like [Symbol.iterator], use the value inside them as the key's name.