Sreekumar P
Sreekumar P

Reputation: 6050

Why “get” method is not there for a ES6 “Set”?

I am talking about ES6's Set function.

let set = new Set();
set.add("1", { Name: "myName", Age: 13 })
set.add("2", { Name: "yourName", Age: 14 })
console.log(set);

To get some value you have to loop through the set and get the value. Ofcouse we can use has method to verify before looping.

But what may be the reason to avoid a get method where we can pass a key to get access to the Values of that?

Upvotes: 2

Views: 73

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075139

You're mistaking Set for Map. Set is for a set of unique values, not key/value mappings. Hence there's no "get" because there's nothing to get; if you have a value that's in the set, you already have it. Map is for key/value mappings.

Your example code is only adding "1" and "2" to the set, not the objects you're passing as the second argument (that second argument is completely ignored by Set.prototype.add).

Map, of course, does have get:

let map = new Map();
map.set("1", { Name: "myName", Age: 13 })
map.set("2", { Name: "yourName", Age: 14 })
console.log(map.get("1"));

Upvotes: 5

Related Questions