How will Javascript Map object improve our coding?
- Anything can be used as a key in a map.
- 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":
- An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null).
- 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.
Again, the keys can be any value!
- Maps are ordered.
- Map keys do not have to be strings