How is a JavaScript Hash Map Implemented?
Last Updated :
20 Dec, 2024
A HashMap (also known as a dictionary or hash table in other programming languages) is a collection of key-value pairs
- Each key in the HashMap is unique, and each key maps to a value. The HashMap allows you to retrieve, update, or delete values by using the associated key.
- In JavaScript, the Map object is an ideal implementation of the HashMap concept, which is part of the ECMAScript 6 (ES6) standard.
JavaScript
const Prices = new Map();
// Add items with their prices
Prices.set('apple', 1.5);
Prices.set('banana', 0.8);
Prices.set('orange', 1.2);
// Retrieve prices
console.log(Prices.get('apple'));
console.log(Prices.get('banana'));
console.log(Prices.get('orange'));
// Check if an item exists
console.log(Prices.has('grapes'));
// Remove an item
Prices.delete('banana');
// Check the size after deletion
console.log(Prices.size);
Output1.5
0.8
1.2
false
2
- Map to store item prices. Items are added with .set()
- values are retrieved with .get()
- The existence of a key is checked using .has()
- The size of the Map is tracked with .size
- Items can be removed with .delete().
Note: In a HashMap (in JavaScript or other languages), keys are unordered, while in a Python dictionary, keys are ordered (since Python 3.7) and maintain insertion order.
How Does a HashMap Work?
- Key-Value Pairs: Data is stored as key-value pairs, where each key is unique, and values can be retrieved using these keys.
- Hash Function: The hash function computes an index (or hash) based on the key. This index determines where the key-value pair should be stored in memory.
- Buckets/Slots: These are storage locations in the array where key-value pairs are stored. If multiple keys map to the same index, collisions occur.
- Collision Handling: When two keys hash to the same index, a collision occurs. Hash maps handle collisions through methods like chaining or open addressing.
- Efficiency: Hash maps provide average constant time complexity (O(1)) for insertion, deletion, and lookup operations, making them highly efficient for large datasets.
Using Map in JavaScript
JavaScript provides the map object, which is an implementation of a HashMap. Map is a collection of key-value pairs where both keys and values can be of any data type.
JavaScript
// Create a new Map (HashMap)
const map = new Map();
map.set('name', 'Amit');
map.set('age', 25);
map.set('location', 'New Delhi');
console.log(map.get('name'));
console.log(map.get('age'));
console.log(map.has('location'));
console.log(map.has('gender'));
map.delete('age');
console.log(map.has('age'));
console.log(map.size);
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
OutputAmit
25
true
false
false
2
name: Amit
location: New Delhi
Hash Collisions and How JavaScript Manages Them
Collisions occur when two different keys hash to the same index. There are two common methods for handling collisions:
1. Chaining (Separate Chaining)
Chaining is a method used to handle hash collisions. When multiple keys hash to the same index, they are stored in a linked list or array at that index.
For Example:
- Hash('apple') -> index 3: stores ('apple', value1)
- Hash('banana') -> index 3: stores ('banana', value2) in a linked list at index 3
When retrieving values, the hash map calculates the hash and checks the index. If there are multiple key-value pairs at the same index, it iterates through the list to find the correct pair.
2. Open Addressing (Probing)
Another approach to handle collisions is open addressing (or probing). It handles collisions by placing the colliding element in the next available slot in the array. There are different probing techniques:(e.g., i+1^2, i+2^2)
- Linear Probing: If a collision occurs at index i, check i+1, i+2, and so on.
- Quadratic Probing: Step size increases quadratically (e.g., i+1^2, i+2^2).
- Double Hashing: Apply a second hash function to find the next available slot.
While efficient, open addressing can lead to clustering, affecting performance.
Example of Collision Handling
JavaScript
const map = new Map();
// Add some key-value pairs
map.set('apple', 1);
map.set('banana', 2);
map.set('apple', 3); // Overwrites the value for 'apple'
console.log(map.get('apple'));
In this example:map.set('apple', 1)
- When map.set('apple', 1) is called, the key 'apple' is hashed and placed in the map.
- When map.set('apple', 2) is called again, the existing key 'apple' is found (due to the hash collision) and its value is updated to 3.
JavaScript ensures that even though apple was added multiple times, the final value is correctly stored.
Use Cases of Hash Maps in JavaScript
- Implementing Caching Systems: Hash maps are widely used in caching systems to store results of expensive function calls and avoid recomputing them.
- Counting Frequencies: Hash maps are useful for counting the frequency of elements in datasets (e.g., word frequency in a text).
- Unique Data Storage: Hash maps are great for ensuring uniqueness in a collection, like storing unique user IDs.
Similar Reads
Implementation of Graph in JavaScript
Implementing graphs in JavaScript is crucial for visualizing data structures and relationships. JavaScript provides various ways to create and manage graphs, including adjacency lists, adjacency matrices, and edge lists. This guide will cover the basics of graph implementation in JavaScript, demonst
6 min read
How to Sort a Map in JavaScript?
Sorting a Map in JavaScript involves ordering its key-value pairs based on the keys or values. Since Maps maintain the insertion order, you can't directly sort them like arrays. Instead, you'll need to convert the Map into an array, sort it, and then convert it back into a Map.Below are the approach
3 min read
Interesting Facts About Map in JavaScript
JavaScript Map is used to store the data of key-value pairs. It can be used to store any type of value including objects and primitive data types. It is iterable which is the main reason we can manipulate it according to the need.Map Internally Uses Hash TableJavaSctipt Map internally uses Hashing t
4 min read
How are elements ordered in a Map in JavaScript ?
In JavaScript, a new object called Map was introduced in the ES6 version. A map is a collection of elements where each element is stored in a key, value pair. Map objects can store both objects as well as primitive data types. The elements of a map are iterable. Elements are always iterated in the i
2 min read
How to convert a Map into a Set in JavaScript?
Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, the
4 min read
Hashing in JavaScript
Hashing is a popular technique used for storing and retrieving data as fast as possible. The main reason behind using hashing is that it performs insertion, deletion, searching, and other operations Why use Hashing?In hashing, all the operations like inserting, searching, and deleting can be perform
6 min read
Map to Array in JavaScript
In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
3 min read
How to serialize a Map in JavaScript ?
In this article, we will discuss, the serialization of maps in JavaScript. Serialization is the conversion of an object or a data structure to another format that is easily transferrable on the network. In JavaScript, the format suitable for transferring is JSON string. So, we usually call the JSON.
2 min read
JavaScript Index inside map() Function
In JavaScript, the map() functionâs callback provides an optional second parameter, the index, representing the current element's position in the array. This index starts at 0 and increments for each element, allowing access to each itemâs position during iteration.Syntax:array.map(function(currente
3 min read
How to create hash from string in JavaScript ?
To create a unique hash from a specific string, it can be implemented using its own string-to-hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256, and many more. These are the fo
3 min read