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
Object
s have been used as Map
s 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
Map
can be any value. eg. objects, functions, etc. Object
s can be Strings and Symbols only
Order of keys
Map
s maintain insertion orderObject
s do not guarantee order
Key Uniqueness
Map
keys are unique; he usesSameValueZero
algorithmObject
string keys are unique
Iteration
Map.prototype.forEach
andfor...of
iterates in insertion order.Object
iteration order can be unpredictable
Built-in Methods
Map
hasset
,get
,has
,delete
andclear
Object
only hasObject.keys
,Object.values
,Object.entries
Size Property
Map
has asize
property that returns the number of key-value pairsObject
has 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]}`)
})