Creating a hash table using Javascript

Let us set up a simple class that we'll use to define all these methods on. We'll create a container object to store the hash table and create a display function to display the table. Note that for collision resolution, we'll use chaining.

The display function takes each entry (hashed value) in the table and prints all pairs associated with it.


We'll also create a new class on the prototype to store the key-value pairs.

class HashTable {
   constructor() {
      this.container = [];
      // Populate the container with empty arrays
      // which can be used to add more elements in
      // cases of collisions
      for(let i=0; i < 11; i ++ ) {
      display() {
         this.container.forEach((value, index) => {
            let chain = value
            .map(({ key, value }) => `{ ${key}: ${value} }`)
            .join(" --> ");
            console.log(`${index}: ${chain}`);
      hash(key) {
         return key % 11;
   HashTable.prototype.KVPair = class {
      constructor(key, value) {
         this.key = key;
         this.value = value;

We're using some advanced features like destructuring in the display method. That helps avoid boilerplate code.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 15-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started