JavaScript keyed collections are structured collections of data that store values and provide methods for easily accessing them.
Keyed collections were actually introduced with ES6 as an alternative to array and object, which were the only data structure available in JS to that point. Although they were good enough for storing data, objects and array had some limitations and were a bit painful to work with.
Keyed collections – namely, Map, Set, WeakMap, and WeakSet – were introduced to solve these issues and to make working with values or key-value pairs easier.
Maps
Map object
A Map object is a simple key/value map and can iterate its elements in insertion order.
Methods are properties are:
new Map()– create the map.map.set(key, value)– stores the value by key.map.get(key)– returns the value by the key, undefined if key doesn’t exist in map.map.has(key)– returnstrueif thekeyexist,falseotherwise.map.delete(key)– removes the element (the key/value pair) by the key.map.clear()– removes everything from the map.map.size– return the current element count.
Example
let map = new Map();
map.set(1, 'Map 1');
map.set('2', 'Map 2');
map.set(true, 'Map 3');
console.log( map.get(1)) // Map 1
console.log( map.get(true)) // Map 3
console.log(map.size); // 3
Set
A set is a special type collection – “set of values” (without keys), where each value may occur only once.
Its main methods are:
new Set([iterable])– creates the set, and if aniterableobject is provided (usually an array), copies values from it into the set.set.add(value)– adds a value, returns the set itself.set.delete(value)– removes the value, returnstrueifvalueexisted at the moment of the call, otherwisefalse.set.has(value)– returnstrueif the value exists in the set, otherwisefalse.set.clear()– removes everything from the set.set.size– is the elements count.
The main feature is that repeated calls of set.add(value) with same value don’t do anything. That’s the reason why each value appears in a Set only once.
For example, we have visitors coming, and we’d like to remember everyone. but repeated visits should not lead to duplicates. A visitor must be “counted” only once.
Set is just the right thing for that:
let set = new Set();
let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };
// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);
// set keeps only unique values
alert( set.size ); // 3
for (let user of set) {
alert(user.name); // John (then Pete and Mary)
}