0
0
JavascriptHow-ToBeginner · 4 min read

How to Implement Hash Table in JavaScript: Simple Guide

To implement a hash table in JavaScript, create a class that uses an array to store key-value pairs and a hash function to convert keys into array indices. Use methods like set(key, value) to add items and get(key) to retrieve values efficiently.
📐

Syntax

A hash table implementation typically includes a class with an internal array to store data, a hash function to convert keys into array indices, and methods to set, get, and remove key-value pairs.

  • constructor(size): initializes the storage array with a fixed size.
  • hash(key): converts a string key into a numeric index.
  • set(key, value): stores the value at the hashed index.
  • get(key): retrieves the value for the given key.
  • remove(key): deletes the key-value pair.
javascript
class HashTable {
  constructor(size = 42) {
    this.buckets = new Array(size);
  }

  hash(key) {
    let hashValue = 0;
    for (let char of key) {
      hashValue += char.charCodeAt(0);
    }
    return hashValue % this.buckets.length;
  }

  set(key, value) {
    const index = this.hash(key);
    if (!this.buckets[index]) {
      this.buckets[index] = [];
    }
    // Check if key exists and update
    for (let pair of this.buckets[index]) {
      if (pair[0] === key) {
        pair[1] = value;
        return;
      }
    }
    this.buckets[index].push([key, value]);
  }

  get(key) {
    const index = this.hash(key);
    if (!this.buckets[index]) return undefined;
    for (let pair of this.buckets[index]) {
      if (pair[0] === key) {
        return pair[1];
      }
    }
    return undefined;
  }

  remove(key) {
    const index = this.hash(key);
    if (!this.buckets[index]) return false;
    for (let i = 0; i < this.buckets[index].length; i++) {
      if (this.buckets[index][i][0] === key) {
        this.buckets[index].splice(i, 1);
        return true;
      }
    }
    return false;
  }
}
💻

Example

This example shows how to create a hash table, add key-value pairs, retrieve values, and remove a key.

javascript
const table = new HashTable(10);
table.set('apple', 100);
table.set('banana', 200);
console.log(table.get('apple'));
console.log(table.get('banana'));
table.remove('apple');
console.log(table.get('apple'));
Output
100 200 undefined
⚠️

Common Pitfalls

Common mistakes when implementing hash tables include:

  • Not handling collisions properly, which can cause data loss.
  • Using a poor hash function that causes many keys to map to the same index.
  • Not updating existing keys when setting a value.
  • Assuming keys are only strings without handling other types.

Always use collision handling like chaining (arrays at each bucket) and check for existing keys before adding new pairs.

javascript
class BadHashTable {
  constructor(size = 10) {
    this.buckets = new Array(size);
  }

  // Poor hash: always returns 0
  hash(key) {
    return 0;
  }

  set(key, value) {
    this.buckets[this.hash(key)] = [key, value];
  }

  get(key) {
    const pair = this.buckets[this.hash(key)];
    if (pair && pair[0] === key) {
      return pair[1];
    }
    return undefined;
  }
}

// This will overwrite values because of no collision handling
const badTable = new BadHashTable();
badTable.set('a', 1);
badTable.set('b', 2);
console.log(badTable.get('a')); // undefined
console.log(badTable.get('b')); // 2
Output
undefined 2
📊

Quick Reference

  • hash(key): Converts key to index.
  • set(key, value): Adds or updates key-value pair.
  • get(key): Retrieves value by key.
  • remove(key): Deletes key-value pair.
  • Collision handling: Use chaining (arrays) to store multiple pairs at one index.

Key Takeaways

Implement a hash function to convert keys into array indices.
Use arrays at each bucket to handle collisions (chaining).
Always check for existing keys before adding or updating values.
Removing keys requires searching the bucket and deleting the pair.
Poor hash functions or no collision handling cause data loss.