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
  • 836
  • 8
  • 24
  • 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

0 Answers0