Map objects are a collection of key-value pairs. They are iterable by insertion order and values are inserted by the set() method. Each key must be unique in the collection too.
Objects vs Maps
Objects have been used as Maps historically since both let you set keys to values, retrive values, delete keys and check if a key exists.
Here are a few differences between the two:
Key Types
- A
Mapcan be any value. eg. objects, functions, etc. Objects can be Strings and Symbols only
Order of keys
Maps maintain insertion orderObjects do not guarantee order
Key Uniqueness
Mapkeys are unique; he usesSameValueZeroalgorithmObjectstring keys are unique
Iteration
Map.prototype.forEachandfor...ofiterates in insertion order.Objectiteration order can be unpredictable
Built-in Methods
Maphasset,get,has,deleteandclearObjectonly hasObject.keys,Object.values,Object.entries
Size Property
Maphas asizeproperty that returns the number of key-value pairsObjecthas no size property. However, you can doObject.keys(myObj).length.
Setting a Map:
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set(3, 'value2')
console.log(map.get('key1')); // Output: value1
console.log(map.size); // Output: 3
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
})
Setting an Object:
const obj = {
key1: 'value1',
key2: 'value2'
}
obj.key3 = 'value3'; // keys must be strings or symbols
console.log(obj.key1);
// iteration
Object.keys(obj).forEach(key => {
console.log(`${key} : ${obj[key]}`)
})