JavaScript does not have a built-in hashmap data structure, but you can implement one using objects. In JavaScript, objects can be used as maps, where you can store key-value pairs.
The syntax for creating an object in JavaScript.
Here, we declare a constant variable myMap
and assign an empty object to it using curly braces {}
.
const myMap = {};
To add key-value pairs to the map use the bracket notation:
myMap['key'] = 'value';
Access the value associated with a key in the map using the bracket notation.
const value = myMap['key'];
Check if a key exists in the map using the in
operator as follows:
if ('key' in myMap) {
// do something
}
Remove a key-value pair from the map using the delete
operator:
JavaScript hashmap example
Simple example code While JavaScript doesn’t have a built-in hashmap data structure, you can implement one using objects.
<!DOCTYPE html>
<html>
<body>
<script>
const myMap = {};
// Adding key-value pairs to the map
myMap['apple'] = 2;
myMap['banana'] = 3;
myMap['orange'] = 5;
// Accessing values using keys
console.log(myMap['apple']); // output: 2
// Checking if a key exists in the map
if ('apple' in myMap) {
console.log('apple exists in the map');
} else {
console.log('apple does not exist in the map');
}
// Removing a key-value pair from the map
delete myMap['banana'];
// Iterating over key-value pairs in the map
for (const key in myMap) {
console.log(`${key}: ${myMap[key]}`);
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this Js Hashmap topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version