DEV Community

M.Ark
M.Ark

Posted on

Maps in JavaScript

Maps, present a lookup via a key, with the difference being that maps retain the type of the key (vs. coercing them into strings like objects do).
Maps offer us a constructor as a means to create new maps.

Unlike arrays and objects, they do not offer us a literal for construction, which has an implication on their serializability.
Maps also offer us a comprehensive API to add, update, and delete keyvalue pairs within the map, all of which we demonstrate here.

const obj = {};
const map = new Map(); ①
map.set('string', 'is a string'); ②
map.set(true, 'is a boolean');
map.set(1, 'is a number').set(obj, 'is an object'); ③
console.assert(map.has(1)); ④
console.assert(map.get(obj) === 'is an object'); ⑤
map.set(1, 'overrides first'); ⑥
console.assert(map.get(1) === 'overrides first'); ⑦
console.assert(map.delete('string')); ⑧
console.assert(map.has('string') === false);
console.assert(map.delete({}) === false); ⑨
Enter fullscreen mode Exit fullscreen mode

① Constructor to create a map
② set a key
③ set is a fluent API returning the map itself
④ has implies possession
⑤ get is the interrogation API
⑥ Forcing a collision causes the previous value to be overwritten
⑦ Last one wins
⑧ If an existing key is deleted then the map returns true
⑨ Deletion of a nonexistent key

The Map API provides us with all we need to work with keys and values.
The set API being fluent certainly proves to be a worthy ally, allowing to avoid some of the verbosity that results if that were not the case.
Collisions are handled as we might expect, and
finally, we can use the delete API to remove a key-value pair from the map, which returns true if the key was indeed deleted from the map.

Top comments (0)