JavaScript

Hash Tables in JavaScript | Explained

Data structures are utilized in computer programming to organize data and apply algorithms for coding. Therefore, understanding data structures and algorithms is beneficial for problem-solving and is required to pass coding interviews.

This write-up will discuss one such top data structure known as “Hash Table” that is considered ideal for storing a large amount of data. Hash Tables can be also used for unique data representation, database indexing, searching in unsorted or sorted arrays.

Now, let’s dive deep into the working and implementation of Hash Tables in JavaScript.

Hash tables in JavaScript

In JavaScript, a “hash table” is a data structure that can be utilized to map keys to their specified values. It is also known as a “hash map“. Hash tables efficiently perform the insertion and deletion operation for a key-value pair and search the value of a key within a hash table.

Components of Hash Tables in JavaScript

There exist two components of Hash tables in JavaScript: an “Object” and a “Hash Function”:

  • Object: An object contains the hash table in which the data is stored. It holds all the “key-value” pairs of the hash table. Also, its size should be determined by the size of expected data.
  • Hash Function: A Hash Function is defined for a hash table to find out the “index” of the given key-value pair. This function accepts a “key” as an input and then assigns a specific “index” and sets that as the return case.

Till this point, you have understood the concept of Hash Tables in JavaScript. Now, let’s head towards its implementation side.

How to implement Hash Tables in JavaScript

For the basic implementation of hash tables in JavaScript, you need to perform these three operations:

  • Firstly, create a class for the hash table.
  • Define a hash function.
  • Define a method for adding key-value pairs for the hash tables.

We will step into the first operation and create a “HashTable” class in our JavaScript program.

Step 1: Create a class for the hash table

Our “HashTable” class comprises a the following “constructor”, in which we have declared an “object”, its “length”, and the hash table “size”:

class HashTable {
    constructor() {
        this.object= {};
        this.size = 0;
        this.length = 0;
  }
}

Step 2: Define a hash function

In the next step, we will define a “hashFunc()” hashing function that accepts “key” as an argument and calculates its “arithmetic modulus” and return the resultant value:

hashFunc(key) {
        return key.toString().length % this.size;
    }

In our “HashTable” class, we will now add a function named “addPair()” for adding the key-value pairs to the hash table.

Step 3: Define a method for adding key-value pairs for the hash tables

In the following “addPair()” function, the first operation which is going to be performed is the calculation of “hash” for the key specified as an argument, with the help of the “hashFunc()” function.

Next, an “if” condition verifies if the calculated “hash” does not already exist in the “object”, then stores the hash to it. After doing so, the stored “hash” will be tested that if it does not contains any “key”, then increment the length “object” and add the “key-value” pair to the hash table object:

addPair(key, value) {
    const hash = this.hashFunc(key);
    if (!this.object.hasOwnProperty(hash)) {
         this.object[hash] = {};
    }
    if (!this.object[hash].hasOwnProperty(key)) {
          this.length++;
    }
        this.object[hash][key] = value;
}

Want to search for a key in the hash table? For this purpose, you have to define a “searchFunction()” in your “HashTable” class. This “searchFunction()” will accept a “key” as an argument and calculate its “hash” by utilizing the “hashFunc()” hashing function.

After that, an “if” condition is added in the “searchFunction()” which validates if the hash table “object” has the calculated “hash” and the specified “key” exists for that “hash”. So, in case the added “if” statement evaluates to be “truthy”, then the stored value for the passed argument will be returned:

searchFunction(key) {
    const hash = this.hashFunc(key);
    if (this.object.hasOwnProperty(hash) && this.object[hash].hasOwnProperty(key)) {
            return this.object[hash][key];
        } else {
            return null;
        }
    }

Add all of the above-given functions in your “HashTable” class and then create an instance to use the defined functions:

const hashtable = new HashTable();

Now, we will add the following three “key-value” pairs in our created “hashtable” object:

hashtable.addPair("Alex", "01");
hashtable.addPair("Stepheny", "23");
hashtable.addPair("Max", "90");

Lastly, we will utilize the “searchFunction()” to find the value of the “Stepheny” key:

console.log(hashtable.searchFunction("Stepheny"));

The given output signifies that we have successfully retrieved the value of the specified key from the hash table:

That was all of the essential information related to Hash Tables in JavaScript. You can further research according to your requirements.

Conclusion

Hash Table in JavaScript is a data structure that can be utilized to map keys to their specified values. It is mainly based on two components: an Object and a Hash Function, where the object contains the hash table in which the data is stored and holds all the “key-value” pairs of the hash table, and the Hash Function is used to determine the “index” of the specified key-value pair. This write-up discussed the concept of Hash Tables in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.