M.dev()

Data structure - Map

Data structure - Map

22.11.2022

Javascript

Why Map and not good old object?!

Like objects Maps are storing key-value pairs and in this sense, are quite alike, BUT in objects the keys must be string, integer(internally converted to string) or Symbol. On the other hand, keys in Map can be any value: functions, objects, abstract data structure and any primitive.

Order

Maps keeps the entry insertion order, keys in objects are ordered now, but this was not always the case, and still is not a great idea to trust the order 100%.

Size

Map has 'size' property, for object we need to do it manually.

Iteration

Map has iterable objects must use Object.entries, Object.keys or Object.values.

1const map = new Map(); 2 3map.set('fistKey', 'foo'); 4map.set('secondKey', 'bar'); 5const fnKey = () => {}; 6map.set(fnKey, 'i am a function key'); 7 8map.get('fistKey'); //foo 9map.get(fnKey); //'i am a function key' 10 11map.size; //3 12 13for (const [k, v] of map) { 14 console.log(k, v); 15} 16/* 17fistKey foo 18secondKey bar 19function fnKey() i am a function key 20*/ 21 22

Map is very straightforward easy to use data structure, with well implemted and self explanatory methods, and some extra cool stuff like iterable and size prop!