theonlychase
5/12/2019 - 8:43 PM

Maps and Weak Maps

Map

  1. Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

  2. Maps Main Methods

    1. new Map() - creates the map
    2. map.set(key, value) - stores value by key
    3. map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
    4. map.has(key) – returns true if the key exists, false otherwise.
    5. map.delete(key) – removes the value by the key.
    6. map.clear() – clears the map
    7. map.size – returns the current element count.
let map = new Map();

map.set('1', 'str1');   // a string key
map.set(1, 'num1');     // a numeric key
map.set(true, 'bool1'); // a boolean key

// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
alert( map.get(1)   ); // 'num1'
alert( map.get('1') ); // 'str1'

alert( map.size ); // 3