0

I'm new to Typescript and Javascript, just a question on Symbol.iterator. We know that we can define an iterable class as:

class iterableExample<T> {
   private items: Map<string, T>;
   ...
   [Symbol.iterator]():Iterator<T> {
       return this.items.values();
   }
}

But what's the syntax of [Symbol.iterator]()? I think it is index signature but it also looks like a method, how could an index signature also be a method? it is really weird.

  • 3
    `Symbol` is a global object. `Symbol.iterator` references the `iterator` property of that object. `[Symbol.iterator]` uses bracket notation to indicate that when looking up the `[Symbol.iterator]` key on the object, the following value gets returned. `[Symbol.iterator]() {` indicates that it's a method, rather than a plain property. – CertainPerformance Sep 25 '19 at 02:07
  • For more information check this out [`symbol.iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) – Code Maniac Sep 25 '19 at 02:10
  • Maybe the confusion came from the computed property names? https://stackoverflow.com/questions/34831262/what-do-square-brackets-around-a-property-name-in-an-object-literal-mean – Kaiido Sep 25 '19 at 02:13
  • See the resulting output: http://www.typescriptlang.org/play/ – user2864740 Sep 25 '19 at 02:22

0 Answers0