Javascript - Collection Map


ES6 Map and WeakMap are fundamentally a hash table.

ES6 Maps provide a simple API to store objects by an arbitrary key.

In Map, both objects and primitive values can be used as either a key or a value.

Keys can be of any type: string, Boolean, number, object, or function.

let myMap = new Map(); 

const keyString = "a string", 
keyObj = {}, 
keyFunc = () => {}; 

// setting the values 
myMap.set(keyString, "value mapped by 'a string'"); 
myMap.set(keyObj, "value mapped by keyObj"); 
myMap.set(keyFunc, "value mapped by keyFunc"); 

The set() method is chainable so you can do this:

myMap.set(keyString, "value mapped by 'a string'") 
     .set(keyObj, "value mapped by keyObj") 
     .set(keyFunc, "value mapped by keyFunc"); 

console.log(myMap.size); // 3 

// getting the values 
myMap.get(keyString);    // "value mapped by 'a string'" 
myMap.get(keyObj);       // "value mapped by keyObj" 
myMap.get(keyFunc);      // "value mapped by keyFunc" 

Related Topics