anotherOne
anotherOne

Reputation: 1573

Why Symbol.iterator was designed of type Symbol?

I am learning about Symbol and iterators in JavaScript. I've read and watched few videos about them, so they are now more or less clear.

I just would like to understand what my textbook (Eloquent JavaScript) means with this:

Note that the next, value and done property names are plain strings, not symbols. Only Simbol.iterator, which is likely to be added to a lot of different objects, is an actual symbol.

Why does a property that is likely to be found in different objects need to be a symbol?

Can objOne.iterator and objTwo.iterator as regular properties create problems?

Upvotes: 2

Views: 179

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370589

Symbols are unique properties on objects. If one creates a symbol and puts it on an object, there's no chance of any other symbol being put on the object and causing bugs due to a name collision.

Using Symbol.iterator as the unique symbol for iterators for potentially any object eliminates the possibility of property collision bugs. For example, if .iterator was the (string) property used instead, objects could no longer easily have the .iterator property unless it specifically implemented the iterator protocol.

Also consider legacy code that might have had objects with an iterator property, but weren't intended to be ES2015+ iterators - what should happen with them? Better to use a Symbol so as not to have to worry about any of that stuff.

anyPossibleObj[Symbol.iterator] is much safer than anyPossibleObj.anyStringYouCouldThinkOf.

Upvotes: 3

Related Questions