José Salgado
José Salgado

Reputation: 1072

Why Sets are considered keyed collections in JavaScript?

I noticed that Sets are being classified as keyed collections, and according the definition is a:

collections of data which are ordered by a key

but aren't the Set keys the values indexes? I'm not sure why they aren't classified as indexed collection just like Arrays.

Thanks!

Upvotes: 0

Views: 246

Answers (2)

Limbo
Limbo

Reputation: 2290

Sets have is not indexed collection, because each value of the Set is unique and cannot be duplicated. Values in Sets are being stored in order of adding, so there is no necessary to create indexes for Set.

I mean, you don't need indexes, when you can get the value of Set ...by it's value! The key of the Set is the value itself. Yes, you can manually check the index of the value by using for ... of cycle. But the use-case of this is pretty weird.

Also, the Set can be used to remove duplicates from existing Array, and, again, indexes have no power here.

I don't know, did I answer your question or not, but it is pretty clear, I suppose :)

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138287

Because you can't access the first/second/third ... entry.

The term "index" is coined as the position in an ordered collection in JavaScript¹. Sets and Maps could be seen as unordered (altough they can be iterated in insertion order), therefore they have no indices, just keys.

¹ I would say that other languages / databases / etc. do coin the term differently.

Upvotes: 0

Related Questions