Hash Maps
A hash map stores key to value pairs and looks any key up almost instantly, whatever the size. JavaScript has two: the plain object for string keys, and Map, which allows any key type and remembers insertion order.
const map = new Map()
map.set("sam", 29)
console.log(map.get("sam")) // 29
console.log(map.has("alex")) // false
A classic use is counting. Run this word counter:
Try it yourself
Loading editor…
Lookup, insert and delete in a hash map are O(1) on average — that is why they are everywhere. Use a Map when keys are not plain strings, or when you add and remove a lot.