Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will Javascript Map object improve our coding?

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?

like image 845
Vandervals Avatar asked May 26 '15 08:05

Vandervals


2 Answers

  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!

like image 170
Sze-Hung Daniel Tsui Avatar answered Oct 17 '22 01:10

Sze-Hung Daniel Tsui


  • Maps are ordered.
  • Map keys do not have to be strings
like image 33
Quentin Avatar answered Oct 17 '22 01:10

Quentin