0

I am new in TypeScript and stumbled over this piece of code:

let numbers = {
  *[Symbol.iterator]() {
    for (let i = 0; i <= 2; i++) {
      yield i;
    }
  },
};

I wonder why the square brackets around Symbol.iterator are needed.

Johannes Schacht
  • 930
  • 1
  • 11
  • 28
  • 1
    The square brackets allow an arbitrary expression to be evaluated. The result of that evaluation will be used as the property key. Keys can be either strings or Symbol instances, so in this case what you end up with is a property whose "name" is the system "iterator" Symbol instance. – Pointy Apr 26 '21 at 21:18
  • Thank you. But why not just omit the square brackets? – Johannes Schacht Apr 26 '21 at 21:37
  • Because it would be a syntax error. – Pointy Apr 26 '21 at 21:38
  • @Pointy what do you mean "by _system_ "iterator" Symbol instance"? Symbol.iterator is not an instance, it's a Symbol. That is also the static property of the _incomplete_ constructor "Symbol" – Shahzad Rahim Jun 21 '22 at 08:15
  • @ShahzadRahim every individual Symbol created is an instance of the Symbol type. Yes, you cannot use `new Symbol()`, but that doesn't mean that individual Symbols are not instances. – Pointy Jun 21 '22 at 11:46

0 Answers0