
Short answer: a hash is a fixed-size value computed from some data by a hash function. A hash table uses that value to decide where to store each key, so it can find the key again in one jump instead of searching through everything. That is why lookups take O(1) time on average.
In JavaScript you use hash tables every day: Map, Set and plain objects all behave like one. This post shows how they work inside, with a small implementation you can run.
What is hashing?
Hashing means running data through a function that turns it into a number (or a short string). A hash function for a hash table needs three properties:
- Deterministic: the same input always gives the same hash.
- Fast: it runs on every lookup, so it must be cheap.
- Well spread: different inputs should land on different values as evenly as possible.
A hash is not unique. There are infinitely many possible strings and only so many hash values, so two different keys will sometimes get the same hash. That is called a collision, and every hash table has to handle it.
How a hash table works
- The table keeps an array of buckets.
- To store a key, it hashes the key and takes the result modulo the number of buckets. That gives a bucket index.
- The key and value go into that bucket.
- To look the key up later, it hashes the key again, goes straight to the same bucket and checks only the few entries there.
Step 2 is the % operator: hash % 8 always gives a number from 0 to 7, which fits an array of 8 buckets. If % is new to you, see the JavaScript modulo operator.
Collisions: chaining vs open addressing
When two keys land in the same bucket, there are two common fixes:
- Separate chaining: each bucket holds a small list. Colliding keys just share the list. Simple, and what the example below uses.
- Open addressing: each slot holds one entry. On a collision, the table probes other slots (for example the next one, called linear probing) until it finds a free one. Lookups follow the same probe sequence. It avoids extra lists but needs care when deleting.
Either way, a lookup only gets slow when many keys pile into the same place. In the worst case (every key collides) a lookup degrades to O(n).
Load factor and resizing
The load factor is the number of entries divided by the number of buckets. As it rises, buckets get longer and lookups slow down. So hash tables resize: when the load factor passes a threshold, they allocate more buckets (often twice as many) and re-insert every entry, because each key’s bucket index depends on the bucket count.
One resize is O(n), but it happens rarely enough that inserts stay O(1) on average (amortized). The example uses a threshold of 0.75, a common choice.
A tiny hash table in JavaScript
Separate chaining, a simple string hash, and resizing. It’s for learning; in real code use Map.
function hash(key, bucketCount) {
let h = 0;
for (const char of String(key)) {
h = (h * 31 + char.codePointAt(0)) % bucketCount;
}
return h;
}
class HashTable {
constructor(bucketCount = 8) {
this.buckets = Array.from({ length: bucketCount }, () => []);
this.size = 0;
}
set(key, value) {
const bucket = this.buckets[hash(key, this.buckets.length)];
const entry = bucket.find(([k]) => k === key);
if (entry) {
entry[1] = value;
return;
}
bucket.push([key, value]);
this.size++;
if (this.size / this.buckets.length > 0.75) this.resize();
}
get(key) {
const bucket = this.buckets[hash(key, this.buckets.length)];
const entry = bucket.find(([k]) => k === key);
return entry ? entry[1] : undefined;
}
delete(key) {
const bucket = this.buckets[hash(key, this.buckets.length)];
const index = bucket.findIndex(([k]) => k === key);
if (index === -1) return false;
bucket.splice(index, 1);
this.size--;
return true;
}
resize() {
const entries = this.buckets.flat();
this.buckets = Array.from({ length: this.buckets.length * 2 }, () => []);
for (const [key, value] of entries) {
this.buckets[hash(key, this.buckets.length)].push([key, value]);
}
}
}
const table = new HashTable();
table.set('apple', 1.2);
table.set('banana', 0.5);
table.set('apple', 1.5); // updates the existing key
table.get('apple'); // 1.5
table.get('cherry'); // undefined
table.size; // 2
table.delete('banana'); // true
table.size; // 1A few things to notice:
- The hash multiplies by 31 and adds each character code, a classic simple string hash. Taking
% bucketCountat each step keeps the number small. - With 8 buckets,
'apple','elder'and'mango'all hash to bucket 2. That is a collision, and chaining handles it: the bucket just holds three entries. - After inserting 1,000 keys the table had grown to 2,048 buckets and the longest bucket held 4 entries, so every lookup checked at most 4 keys.
- It compares keys with
===, so1and'1'hash the same (the hash usesString(key)) but stay separate entries.
Map, Set and objects in JavaScript
The spec requires Map and Set to use “hash tables or other mechanisms” with sublinear average access time, and engines use hash tables. Map accepts any key type (objects included) and remembers insertion order. Set stores unique values. Both have a size property. See MDN’s Map reference for the full API.
Plain objects also work as a lookup table, with two catches: keys are converted to strings (or symbols), and objects inherit keys like toString from Object.prototype. Use Object.hasOwn() to check keys, or prefer Map when keys come from user input.
const prices = new Map();
prices.set('apple', 1.5);
prices.set(42, 'a number key');
const user = { id: 1 };
prices.set(user, 'an object key');
prices.get('apple'); // 1.5
prices.has(user); // true
prices.size; // 3
const seen = new Set(['a', 'b', 'a']);
seen.size; // 2
seen.has('b'); // true
const obj = {};
obj[1] = 'one';
Object.keys(obj); // ['1'] (the number became a string)
'toString' in {}; // true (inherited)
Object.hasOwn({}, 'toString'); // falseWhere hash tables show up
- Counting: word frequencies, votes, page views per URL.
- Removing duplicates:
[...new Set(array)]. - Caching: store results by input so you compute each one only once (memoization).
- Indexing: turn an array of users into a
Mapbyidso you stop callingfind()in a loop. That turns anO(n²)pattern intoO(n).
Hashing vs encryption
The word “hash” also means something stronger in security. A cryptographic hash such as SHA-256 is designed so that you can’t work backwards from the hash to the input, and so that finding two inputs with the same hash is infeasible. Change one character and the whole hash changes. Encryption is different: it is meant to be reversed by anyone with the key. Hashing is one-way; encryption is two-way.
Don’t invent your own versions of either. A hash-table hash like the one above is not secure. For passwords, don’t use a plain SHA-256 either: use a slow, salted password hashing algorithm such as Argon2 or bcrypt through a well-maintained library, or your framework’s built-in password hashing. In browsers, the Web Crypto API (crypto.subtle.digest()) gives you SHA-256 for checksums and similar non-password uses.
// Node.js: SHA-256 of a string (fine for checksums, not for passwords)
const { createHash } = require('node:crypto');
createHash('sha256').update('hello').digest('hex');
// '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'Hash tables come up in most coding interviews, usually as “can you make this faster?” The answer is often “put it in a Map“. There are more practice resources in this list for technical interviews.
FAQ
What is a hash table in simple terms?
A data structure that stores key-value pairs and uses a hash of each key to jump straight to where it is stored. Lookups, inserts and deletes take constant time on average.
What is a hash?
A fixed-size value computed from data by a hash function. The same input always gives the same hash, but different inputs can occasionally share one.
Is a JavaScript object a hash table?
It behaves like one for lookups, but keys are always strings or symbols and inherited keys can get in the way. Map is the purpose-built hash map in JavaScript.
What happens when two keys have the same hash?
That is a collision. The table either keeps both in a list at that bucket (chaining) or looks for another free slot (open addressing). Both still find the right key by comparing the keys themselves.
Is hashing the same as encryption?
No. A cryptographic hash is one-way and can’t be decrypted. Encryption is designed to be reversed with a key.





