HashMap aka Dictionary aka …

Do you have a need for speed? Do you want to do a search and get the answer right here? Right now? If you do, then hash maps are for you because they have a time complexity of O(1). Before we dig any deeper, you should know the HashMap data structure has alternative names or equivalents across different languages such as dictionary (for C#, Python, Swift), HashTable or HashMap (Java) or Map for Javascript. Even though there are various names, they all are data structures that can map keys to their corresponding values.

With Javascript, we all should be familiar with the key/value pair or functionality. We search up the key to see the value it is associated with. One general example of a HashMap is taking a look at our general folders on our computer. We have a list of folders with names (ie. Music, Video, Pictures etc..) telling us what contents are inside. If we are looking for a photo, given that the file was placed correctly, we just need to go directly to the picture’s folder. The pictures folder is our key, and the photo inside would be our value. We don’t need to open every folder down the list to find a photo.

Although HashMaps are limited to single-threaded code, one of the benefits is that it allows null values which allows for greater flexibility. We already have Javascript objects that represent key/value pairs, so what is the difference between a Javascript object and HashMap? With the update of Javascript ES6, the key in a HashMap can be any datatype, such as arrays and objects. Meanwhile, objects can only use integers, strings, and symbols as their keys. With that, lets use the key/value functionality thats come native in JavaScript (ES6) in the form of the Map() object.

We begin by creating our HashMap data structure using Map() in Javascript and call upon the keys to receive its values. In the example below, I have created an Engineer class with three keys and added four engineers to the list using .set().

We can then use the .forEach() method to call every key of each engineers to see their value. This way we can see each key and value for the engineer’s name, favorite language and their contact number.

After running the following code above, the list should display on the html. Just remember that the data will always follow the order of the original input.

There are other methods that you can use to manipulate or retrieve information on the data structure. To continue learning more, you can take a look at MDN web docs on Javascript’s Map.



Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store