1

I recently learned that to get an iterator from an Array, you have to access it using syntax that I have never seen before: let iterator = myArray[Symbol.iterator]()

It seems to me that implementing Array.prototype.getIterator() would have been a more idiomatic way to go, but I must be oversimplifying or just not understanding the significance of accessing this property of arrays in this particular way.

In attempting to deepen my understanding of the inner workings of JavaScript I was hoping someone could explain this diversion from a more traditional syntax.

S.Orioli
  • 443
  • 6
  • 21
Tom Auger
  • 19,421
  • 22
  • 81
  • 104
  • 2
    Just adding a new method to something like the Array object can have massive consequences and is no simple task. The Symbol syntax is not specific to iterators. The iterator is just one of many common Symbols. Symbols were brought in with ES2015 and one of the big reasons for doing so was to add extra features to things like arrays for example for..of requires iterators which need Symbols. – GifCo May 22 '19 at 14:01
  • https://en.wikipedia.org/wiki/Symbol_(programming) - symbols are nothing new. – Randy Casburn May 22 '19 at 14:05
  • This is not a duplicate of https://stackoverflow.com/questions/21724326/what-is-the-motivation-for-bringing-symbols-to-es6, though, after reading it, that _question_ is the _answer_ to this one: the strange notation is using the new Symbol syntax and using Symbol notation allows the spec to augment existing first-order objects (like Arrays) with new features without accidentally colliding with other user-created properties that might have the same name. – Tom Auger May 24 '19 at 03:43

0 Answers0