JavaScript Hashmaps: Objects vs. the Map Object
JavaScript doesn’t have a direct “HashMap” equivalent like some other languages. However, we can achieve similar functionality using two primary approaches: plain JavaScript objects and the built-in Map
object. This article explores both, comparing their strengths and weaknesses to help you choose the best approach for your needs.
Table of Contents
Using Objects as Hashmaps
JavaScript objects can function as simple hashmaps. They use string keys to access associated values. This approach is straightforward but has limitations.
Example:
const myHashMap = {}; // Create an empty object
// Insert key-value pairs
myHashMap.apple = 1;
myHashMap.banana = 2;
myHashMap.cherry = 3;
// Access values
console.log(myHashMap.banana); // Output: 2
// Check if a key exists
console.log('apple' in myHashMap); // Output: true
// Delete a key-value pair
delete myHashMap.banana;
// Iterate over key-value pairs (Note: order is not guaranteed)
for (const key in myHashMap) {
console.log(key, myHashMap[key]);
}
Advantages:
- Simple and familiar to JavaScript developers.
- No external dependencies.
Disadvantages:
- Keys are limited to strings (or values that implicitly convert to strings).
- No built-in size property; you need to track size manually.
- Lacks built-in methods like
get
,set
,has
, etc. - Key order is not guaranteed.
Using the Map
Object
The Map
object (introduced in ES6) offers a more robust solution. It supports any data type as a key, avoids type coercion issues, and provides built-in methods for efficient manipulation.
Example:
const myMap = new Map();
// Insert key-value pairs
myMap.set("apple", 1);
myMap.set(123, "number"); // Number as key
myMap.set({ a: 1 }, "object"); // Object as key
// Access values
console.log(myMap.get("apple")); // Output: 1
console.log(myMap.get(123)); // Output: "number"
// Check if a key exists
console.log(myMap.has("apple")); // Output: true
// Delete a key-value pair
myMap.delete("apple");
// Get the size
console.log(myMap.size); // Output: 2
// Iterate over key-value pairs (order is preserved)
for (const [key, value] of myMap) {
console.log(key, value);
}
Advantages:
- Supports any data type as a key.
- Provides built-in methods (
set
,get
,has
,delete
,size
). - Efficient iteration with
for...of
loops. - Preserves insertion order.
Disadvantages:
- Requires ES6 compatibility (although polyfills are available).
Conclusion
While plain JavaScript objects can suffice for simple hashmap-like behavior, the Map
object is generally recommended for its superior features and efficiency. Unless you are severely constrained by browser compatibility, Map
is the preferred choice for most modern JavaScript projects.