0

I'm just looking into ES2015, and coming up to Maps, Sets and Arrays.

Question 1

Firstly I'm interested in why they all use a different method to add items to it.

  • Set.add("item");
  • Map.set("item");
  • Array.push("item");

is there method to the madness rather than keeping them all as .push?

Question 2

size vs length.

Why have Map and Set got .size but Array has .length why not use the same?

Question 3

When would you use Map over Array? can anybody give a real world example for this, I understand you can do things like use objects as keys in Maps, but why would you do that in the first place.


Hopefully somebody can clear this up to help inform other new starters to ES2015, thanks.

Community
  • 1
  • 1
Owen
  • 5,225
  • 14
  • 56
  • 102
  • I can't answer all your questions, but I think you're confused about `Map`. It's not array like, it's a key / value store like an Object. But there are important differences to a regular javascript object https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map – azium Sep 09 '16 at 15:04
  • or maybe in your question you meant to ask when you would use a Map over an Object? – azium Sep 09 '16 at 15:15
  • @azium from what I know, if you want to iterate over the element, you'll need to use a Map, as natively Objects cant be looped around – Owen Sep 09 '16 at 15:23

1 Answers1

1

Sets, Maps and Arrays use different methods, because these methods do different things. Array.prototype.push() adds one or more elements to the end of the array. Set.prototype.add() works similarly, but it only accepts one argument. If it was named push(), some people would think that it works the same as the array method, and they'd try doing set.push(1, 2, 3) and they'd be confused why it adds only the first element.

Map.prototype.set() is a completely different thing. From MDN:

The set() method adds or updates an element with a specified key and value to a Map object.

If an element with a specified key already exists, this method doesn't add any element to the Map, but only updates the value of that element.

You second question was answered on this blog:

length is for sequences, data structures that are indexable – like arrays. size is for collections that are primarily unordered – like maps and sets.

I don't really understand your third question. Maps and Arrays are completely different data structures. Maps are similar to objects, see Maps vs Objects in ES6, When to use?

Community
  • 1
  • 1
Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155