Hash Map in JavaScript - Full Course
What is a Hash Map?
A hash map (also known as an object or dictionary) is a data structure that stores key-value pairs. It
allows quick data retrieval based on keys.
Creating a Hash Map in JavaScript
You can create a hash map using an object literal:
let map = {
'name': 'Alice',
'age': 25,
'city': 'New York'
};
Accessing Values
Use the key inside square brackets or dot notation:
console.log(map['name']); // Alice
console.log(map.age); // 25
Adding or Updating Values
To add or update:
map['profession'] = 'Engineer';
map.age = 26;
Deleting Values
Hash Map in JavaScript - Full Course
Use the delete keyword:
delete map.city;
Checking if a Key Exists
Use the in operator or hasOwnProperty method:
'age' in map; // true
map.hasOwnProperty('city'); // false
Iterating Over a Hash Map
Use a for...in loop:
for (let key in map) {
console.log(key + ': ' + map[key]);
Using Map Object (ES6)
let myMap = new Map();
myMap.set('name', 'Bob');
myMap.get('name');
myMap.has('name');
myMap.delete('name');
Advantages of Map over Object
- Maintains insertion order
- Keys can be any data type
Hash Map in JavaScript - Full Course
- Better performance for frequent additions/removals
Use Cases of Hash Maps
- Caching
- Counting frequencies
- Lookup tables
- Storing configuration settings