Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing value to Symbol.iterator

If I define an iterator for an object and create an instance, I can iterator over those values, as expected:

class Hello {
  *[Symbol.iterator]() {
    yield 5;
   }
  *iterator (value) {
    yield value;
  }
}

var hello = new Hello();

for (let val of hello) {
  console.log(val); // 5
}

for (let val of hello.iterator('wow')) {
  console.log(val); // 'wow'
}

In the previous example, the [Symbol.iterator] is declared as a generator. I can declare another generator and pass arguments to it, but is there a way to pass arguments to the default iterator?

I've tried the following, but it throw an error:

for (let val of hello('wow')) {
  console.log(val); // 5
}

// Uncaught TypeError: hello is not a function

Am I missing something? Or is this just not possible?

like image 680
Jorge Silva Avatar asked Sep 10 '26 10:09

Jorge Silva


1 Answers

When you pass a value to be iterated in a for…of loop, it needs to implement the iterable interface - that is, its Symbol.iterator method will be implicitly called with no arguments and should return an iterator.

You also can pass iterators directly, as all iterators are "iterable", their Symbol.iterator method just returns themselves.

So while there is no way to make a for…of loop call the default iterator with special arguments, you always can call the method yourself and pass the iterator:

var hello = {
  *[Symbol.iterator](val) {
    yield val;
  }
};
for (let val of hello[Symbol.iterator]('works')) {
  console.log(val); // 'works'
}
like image 98
Bergi Avatar answered Sep 13 '26 01:09

Bergi