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?
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":
Again, the keys can be any value!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With