Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use an ES6 Map over an Object? [duplicate]

I've been looking at the new ES6 docs on MDN and I can't find a real world use for the Map object where a normal object wouldn't work. Does anyone have any use cases for Maps and explain why an object wouldn't work in that scenario?

like image 367
silverlight513 Avatar asked Feb 09 '23 07:02

silverlight513


1 Answers

MDN lists a number of important differences:

  • An Object has a prototype, so there are default keys in the map. [editor: the good old hasOwnProperty issue]
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to manually keep track of size for an Object.
  • A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.

So a Map is finally an insert-ordered key-value store for Javascript, which additionally allows mapping any value to any value, instead of restricting keys to be strings. This can greatly simplify some code where ordering is important, or where objects or other complex data types need to be associated with other data.

like image 186
deceze Avatar answered Feb 12 '23 01:02

deceze