If arrays are like notebooks where you flip pages one by one, hashmaps are like a magic index. You whisper a key, and the value appears instantly. No searching. No looping. Just speed ⚡
In JavaScript, we use hashmaps all the time, often without even realizing it.
Let’s understand what they are, how JavaScript implements them, and when you should reach for one.
What is a HashMap?
A HashMap is a data structure that stores data as key → value pairs.
Example:
"userId" → 1024
"username" → "varun"
"isAdmin" → true
Instead of storing values in order like an array, a hashmap uses a hash function to convert a key into an index. That’s why:
- Lookup is fast
- Insert is fast
- Delete is fast
In Big-O terms:
- Insert: O(1)
- Lookup: O(1)
- Delete: O(1)
That’s the kind of speed system designers dream about.
HashMaps in JavaScript
JavaScript doesn’t have a class called HashMap, but it gives us two powerful tools that behave like one:
- Objects (
{}) - Map (
new Map())
Let’s look at both.
Using Objects as HashMaps
Objects are the most common and oldest way to create hashmaps in JavaScript.
Example
const user = {
name: "Varun",
role: "Developer",
age: 25
};
console.log(user.name); // Varun
console.log(user["age"]); // 25
Here:
- Keys are strings
- Values can be anything
Adding & Updating Values
user.country = "India";
user.age = 26;
Deleting a Key
delete user.role;
Checking if a Key Exists
if ("name" in user) {
console.log("Name exists");
}
Limitations of Objects as HashMaps
Objects come with some hidden baggage:
- Keys are only strings or symbols
- Inherited properties (
toString,constructor) can cause bugs - Not ideal when keys are dynamic or complex
That’s why JavaScript introduced Map.
Map: A True HashMap in JavaScript
Map is designed specifically for key-value storage.
Creating a Map
const userMap = new Map();
userMap.set("name", "Varun");
userMap.set("age", 25);
userMap.set("isDeveloper", true);
Getting Values
console.log(userMap.get("name")); // Varun
Checking Existence
userMap.has("age"); // true
Deleting Values
userMap.delete("isDeveloper");
Map Size
console.log(userMap.size); // 2
Why Map is Better Than Object
| Feature | Object | Map |
|---|---|---|
| Key Types | Strings only | Any type |
| Order | Not guaranteed | Preserved |
| Performance | Good | Better for large data |
| Size | Manual | .size |
You can even use objects or functions as keys in a Map 🤯
const objKey = { id: 1 };
userMap.set(objKey, "Some value");
Real-World Use Cases of HashMaps
1. Counting Frequency (Classic Interview Question)
const arr = ["a", "b", "a", "c", "b", "a"];
const freq = {};
for (let char of arr) {
freq[char] = (freq[char] || 0) + 1;
}
console.log(freq);
// { a: 3, b: 2, c: 1 }
2. Fast Lookups (Avoid Nested Loops)
const users = [
{ id: 1, name: "A" },
{ id: 2, name: "B" }
];
const userMap = new Map();
users.forEach(u => userMap.set(u.id, u));
console.log(userMap.get(2)); // { id: 2, name: "B" }
3. Caching (Very Important in Backend)
const cache = new Map();
function fetchData(key) {
if (cache.has(key)) {
return cache.get(key);
}
const result = expensiveOperation(key);
cache.set(key, result);
return result;
}
This pattern shows up in:
- Redis logic
- API caching
- Rate limiters
- Session stores
When NOT to Use a HashMap
- When order doesn’t matter and data is tiny → arrays are fine
- When you need sorted data → use trees or sorted arrays
- When memory is extremely limited
Hashmaps trade memory for speed.
HashMap vs Array (Quick Intuition)
| Task | Best Choice |
|---|---|
| Search by key | HashMap |
| Ordered data | Array |
| Frequency count | HashMap |
| Index-based access | Array |
Final Thoughts
Hashmaps are one of those tools that quietly power:
- Search engines
- Caches
- Databases
- Real-time systems
- Interview questions 😄
If you master hashmaps, half of DSA suddenly feels… lighter.