At a small post office, letters aren't thrown into one pile. There's a rack with one box for each first letter of a name: a letter for Budi goes directly into box B. When Budi comes to collect his post, the clerk only has to open one box, however many letters came in that day.
A hash map stores data in much the same way, as pairs of a key and a value. The key is the name you look things up by, like the name Budi. The value is what's stored, like the letter for Budi. From the key, the hash map calculates which box to open, like the clerk who looks at the first letter of the name. That's why getting a value by its key takes about one step on average, however much data there is.
Keys, values and buckets
In JavaScript, the ready-made hash map is called Map. This code stores the stock of three fruits, then reads, checks and removes them:
const stock = new Map();
stock.set("apple", 5);
stock.set("melon", 2);
stock.set("banana", 8);
console.log(stock.get("melon")); // 2
console.log(stock.has("orange")); // false
console.log(stock.get("orange")); // undefined
stock.delete("banana");
console.log(stock.size); // 2
new Map()makes an empty map.set(key, value)stores one pair.get(key)returns its value, orundefinedif that key isn't there.has(key)answerstrueorfalse.delete(key)removes the pair.sizeis the number of pairs. A Map has nolength.
Inside, a hash map has a row of numbered boxes called buckets, like the boxes on the post office rack. Say there are 8 buckets. A hash function is a function that turns the key into a number. The remainder of that number divided by 8 is the bucket number:
| Key | Hash function result | Remainder after dividing by 8 | Goes into bucket |
|---|---|---|---|
"apple" |
93029210 | 2 | 2 |
"melon" |
103780019 | 3 | 3 |
"banana" |
2898612069 | 5 | 5 |
When get("melon") is called, the hash function calculates the same number again. So the hash map goes directly to bucket 3, without opening any other bucket. That's why a hash map is called O(1).
Collisions: two keys, one bucket
Say you call stock.set("papaya", 4): the hash function takes "papaya" to bucket 2, the same as "apple". Two different keys in the same bucket is called a collision. Nothing is overwritten and there's no error: both are kept in bucket 2 as a short list. This approach is called chaining.
get("papaya") then runs in three steps:
- The hash function calculates the bucket number for
"papaya": 2. - The hash map opens bucket 2.
- It checks what's inside bucket 2 one by one:
"apple"no,"papaya"found.
So O(1) in a hash map is the average, not a promise:
- As long as each bucket holds only a few keys, a lookup stays at about one step. As the hash map becomes full, it adds buckets (say from 8 to 16) and spreads the keys again, so the list in each bucket stays short.
- The worst case: every key lands in the same bucket, and a lookup has to check the keys one by one. That's O(n): with twice the data, it takes roughly twice the time. JavaScript's built-in
Mapis designed so this almost never happens.
Counting with Map
A hash map is often used to count how many times something appears. This code counts each fruit in the array shopping:
const shopping = ["apple", "melon", "apple"];
const counts = new Map();
for (const fruit of shopping) {
counts.set(fruit, (counts.get(fruit) || 0) + 1);
}
console.log(counts.get("apple")); // 2
console.log(counts.get("melon")); // 1
console.log(counts.get("orange")); // undefined
console.log(counts.size); // 2
- The first time
"apple"appears,counts.get("apple")is stillundefined.|| 0turns thatundefinedinto 0, then 1 is added. - The second time,
getreturns 1, so 2 is stored. setwith a key that's already there replaces its old value instead of adding a new pair. That's whysizeis the number of different keys (2), not the number of items in the array (3).
Objects are used as hash maps too
A plain object also stores key and value pairs: const prices = { apple: 5 }, then prices["melon"] = 12 adds a pair, and prices["apple"] reads its value. This table compares an object and a Map:
| Object | Map | |
|---|---|---|
| Keys | only text or a Symbol (a unique value made by Symbol()): obj[1] and obj["1"] are the same key |
any type, numbers and objects too |
| Number of entries | Object.keys(obj).length |
map.size |
| Order | number-like keys first, in ascending order, then the rest in the order they went in | always the order they went in |
Use an object for data with fixed field names (property names), like { name, age }. Use a Map when the keys change, are added and removed a lot, or for counting.
⚠️ Why does get return undefined, or the count NaN?
- Square brackets on a Map.
stock["apple"] = 5makes an ordinary property, not an entry in the Map:get("apple")is stillundefinedandsizedoesn't go up. Useset. - Forgetting
|| 0when counting.undefined + 1givesNaN(not a number). - An object as the key. A Map treats two object keys as the same key only when they are the very same object. Equal contents are not enough. After
m.set({ id: 1 }, "Anna")on a Mapm,m.get({ id: 1 })givesundefined, because the second{ id: 1 }is a new object. Keep the object in a variable, then use that variable insetandget. Or use text or a number as the key, such as the id. - Returning an object when a Map was asked for. An object has no
getand nosize. In the exercise, the function has to return a Map, so start fromnew Map().
💡 A hash map often turns two loops into one. Say you want to know whether any value appears twice among 1,000 items. With a loop inside a loop, it takes about half a million comparisons. With one loop, each value is checked with
has, then stored in aMap. That takes only about 1,000 steps.
TL;DR: A hash map stores key and value pairs, and you get a value by its key. A hash function turns the key into a bucket number (a numbered box where the pair is kept), and the hash map goes directly to that bucket. That's why get (read), set (store), has (check whether it's there) and delete (remove) are O(1) on average. Two keys in the same bucket is a collision, and both are still kept as a short list (chaining). If too many keys collect in one bucket, a lookup slows down to O(n). In JavaScript, use new Map(): set with an existing key replaces its value, and size counts the different keys. Counting: map.set(key, (map.get(key) || 0) + 1). Objects store keys and values too, but a number or an object used as a key is turned into text.
⚡ Store and get by key
Write:
const stock = new Map();
stock.set("apple", 5);
stock.set("melon", 2);
console.log(stock.get("melon")); // 2
console.log(stock.has("orange")); // false
Meaning: stock is a Map, JavaScript's built-in hash map, which stores key and value pairs. set stores one pair, get reads the value by its key, and has answers whether the key is there. The number of pairs is in size, not length.
⚡ Buckets and collisions
Guess first: a hash map keeps its pairs in a row of numbered boxes called buckets. "papaya" goes into the same bucket as "apple". What happens?
Nothing is overwritten and there's no error. Both are kept in that bucket as a short list. Two keys in one bucket is a collision, and this way of keeping them is called chaining.
Meaning: A hash function (a function that turns the key into a number) decides each key's bucket number. The hash map opens only that one bucket, so get, set, has and delete (remove) are O(1) on average. If too many keys collect in one bucket, they have to be checked one by one, and a lookup slows down to O(n).
⚡ Counting with a Map
Write:
for (const fruit of shopping) {
counts.set(fruit, (counts.get(fruit) || 0) + 1);
}
Meaning: shopping is an array of fruit names, and counts is a Map that starts empty. The loop counts how many times each fruit appears. The first time a fruit appears, get is still undefined, and || 0 turns that into 0, then 1 is added. Without || 0, you get NaN (not a number). set with a key that's already there replaces its old value, so size is the number of different keys.