What Are Hash Tables?
So you want to learn about hash tables? Trust me, this is one of the most useful data structures you'll ever encounter. A hash table is basically a way to store key-value pairs so you can look things up lightning fast.
Think of it like a dictionary. You don't read every word to find what you're looking for โ you jump straight to the right page. Hash tables work the same way, but even faster. You give it a key, and it hands you the value instantly.
In JavaScript, you already use hash tables without realizing it. Plain objects and the Map class are both hash tables under the hood.
How They Work Internally
Here's the magic trick. When you store a key-value pair, the hash table runs the key through a hash function. That function spits out a number, which becomes the index in an array where your data lives.
So when you ask "hey, give me the value for key X," it hashes X, finds the index, and grabs the value. No searching, no comparing โ just boom, there it is.
This is why hash tables give you O(1) average lookup time. The hash function does all the heavy lifting of figuring out where things go.
const user = {
name: "Alice",
age: 30,
role: "developer"
};
const scores = new Map();
scores.set("math", 95);
scores.set("science", 88);
console.log(user.name);
console.log(scores.get("math"));
Try it Yourself โ
Objects vs Maps
JavaScript objects work great as hash tables, but they have a quirk โ keys must be strings or symbols. If you try to use an object as a key, it just gets converted to a string like "[object Object]."
Maps fix this problem. With a Map, any value can be a key โ objects, functions, even other Maps. Plus Maps remember the order you inserted things, while objects don't guarantee that.
For most day-to-day coding, objects are totally fine. But when you need non-string keys or care about insertion order, reach for a Map.
const objMap = {};
objMap[1] = "one";
objMap["1"] = "also one";
console.log(objMap);
const realMap = new Map();
realMap.set(1, "one");
realMap.set("1", "also one");
console.log(realMap);
Try it Yourself โ