Vandervals
Vandervals

Reputation: 6054

Why use an ES6 Map instead of a plain javascript object?

If we can make key/value pairs with plain javascript objects, then what is the reason to use the new ES6 Map object?

When should I use one and when the other? Is Map limited to values or can it contain functions as well?

Upvotes: 40

Views: 4951

Answers (2)

Quentin
Quentin

Reputation: 943569

  • Maps are ordered.
  • Map keys do not have to be strings
  • Map has a size property that tracks the number of pairs

Upvotes: 15

Sze-Hung Daniel Tsui
Sze-Hung Daniel Tsui

Reputation: 2332

  1. Anything can be used as a key in a map.
  2. Maps are ordered, and that allows for iteration.

Combining 1 and 2, when you iterate over a map, you'll get a useful array of key-value pairs!

Check out the map.prototype.forEach() documentation.

Source: Another good question/answer exchange. Worth marking this one as a duplicate.

Update: Adding to this answer to address the question directly:
You should use a map whenever you need to associate things together or preserve insertion order (common data structures need this).

You can use an object when you don't need to do this, but they just do different things.

Update 2: OP asked if functions are okay too. Yes, because values can be functions too! Check it out:

let x = new Map();
let y = () => {
  console.log('derp');
}
x.set(y, "HI");
console.log(x.get(y)); // will log "HI"

For more info, check out the source of this quote, in a great chapter of Eloquent JavaScript:
"Every value has a type that determines its role. There are six basic types of values in JavaScript: numbers, strings, Booleans, objects, functions, and undefined values."

Also, the main differences between Map and Object, from MDN, under the header "Objects and Maps Compared":

  1. An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null).
  2. The keys of an Object are Strings, where they can be any value for a Map.
  3. You can get the size of a Map easily while you have to manually keep track of size for an Object.

Again, the keys can be any value!

Upvotes: 22

Related Questions