0

Set.prototype.forEach which accepts a callback function in ES6 The function has 3 parameters to be consistent with Map.prototype.forEach. MDN says both the first 2 parameters for the callback are values because there is no keys in Set object. Why the item in Set is considered as value instead of key? No duplicated key in Set object would make more sense because there is also no duplicated key in Map.

Another aspect that value in Set looks like key in Map is that it makes Set.prototype.has(value) and Map.prototype.has(key) more consistent. Duplicated keys are NOT allowed in Array (key is index) and Map, but this cannot be extended to Set which doesn't allow duplicated values. Make it as duplicated keys are not allowed in all containers might be a more succinct rule.

4
  • 2
    A Map object has a key and a value which are separate entities. A Set object just has a value which you use to add the value to the Set and use to test if the value is in the Set. Essentially, a Set is indexed by the value so it's kind of like a Set is a Map where the key and value are the same. Commented Dec 3, 2016 at 20:22
  • Your last edit has driven me to a question to your own question: what's the question? :D Commented Dec 3, 2016 at 20:40
  • @MatíasFidemraizer My last edit added some evidence that calling item in Set as key instead of value might be more appropriate. So my question ist still why the stand calls item in Set as value, not as key. :) Commented Dec 3, 2016 at 22:24
  • It's already answered twice :( Commented Dec 3, 2016 at 22:26

2 Answers 2

2

It's just because the semantics of set collections. A set stores values while a map stores keys and values.

For example, both motorbikes and bicycles own two wheels, but you still say that there're motorbikes and bicycles. Just because set values and map keys are unique doesn't mean that they're the same thing.

Sign up to request clarification or add additional context in comments.

Comments

2

From the MDN link which you have attached.

The are no keys in Set objects. However, the first two arguments are both values contained in the Set, so that the callback function is consistent with the forEach methods for Map and Array.

We can say that set is just an array which keeps distinct elements. There are no keys in sets.

2 Comments

Well most collections have an underlying array storage ;D
Well, we have to start from something :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.