Using Hash Tables for Fast Data Lookup in JavaScript

November, 11th 2024 2 min read

Hash tables (also known as hash maps or dictionaries) are essential for fast data lookup in JavaScript. They provide a way to store and retrieve data quickly using key-value pairs. This guide explains how hash tables work, why they’re useful, and how to implement them in JavaScript.

What Is a Hash Table?

A hash table maps keys to values using a hashing function. This function transforms the key into a numerical index pointing to a storage location. With a good hash function, lookups perform in O(1) time on average.

Benefits

  • Fast lookups
  • Efficient memory usage
  • Perfect for caching, indexing, and unique-key storage

Basic Hash Table Implementation

js
class HashTable {
  constructor(size = 50) {
    this.table = new Array(size);
  }

  _hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      hash += key.charCodeAt(i);
    }
    return hash % this.table.length;
  }

  add(key, value) {
    const index = this._hash(key);
    if (!this.table[index]) this.table[index] = [];
    this.table[index].push([key, value]);
  }

  get(key) {
    const index = this._hash(key);
    const bucket = this.table[index];
    if (!bucket) return undefined;
    for (let [k, v] of bucket) {
      if (k === key) return v;
    }
    return undefined;
  }

  remove(key) {
    const index = this._hash(key);
    const bucket = this.table[index];
    if (!bucket) return false;
    this.table[index] = bucket.filter(([k]) => k !== key);
    return true;
  }
}

Using JavaScript Map

js
const users = new Map();
users.set('id-1', { name: 'Alice' });
console.log(users.get('id-1'));

Conclusion

Hash tables are among the most efficient data structures for key-based lookups. Whether using Map, Object, or a custom implementation, mastering them improves performance in JavaScript applications.