What Does a Hash Function Do?
A hash function takes any input and turns it into a fixed-size number. That's it. It's like a magic machine that accepts anything — strings, numbers, objects — and spits out a number every single time.
The key thing is determinism. If you feed it the same input twice, you must get the same output both times. Otherwise, your hash table would be completely useless.
Think of it like a barcode scanner at a grocery store. Every product gets scanned into a number that the system uses to look up the price. Same product, same barcode, every time.
What Makes a Good Hash Function?
Not all hash functions are created equal. A good one needs to spread values out evenly across the array. If half your keys end up in the same spot, you've got a problem called clustering, and your O(1) lookups turn into O(n) nightmares.
A good hash function also needs to be fast. If computing the hash takes forever, you've defeated the whole purpose. And it should handle different input sizes gracefully — hashing a 3-letter word shouldn't be way slower than hashing a 10-letter word.
The best hash functions are nearly impossible to predict. You shouldn't be able to look at two keys and guess whether they'll land in the same bucket.
function simpleHash(key, size) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash % size;
}
console.log(simpleHash("cat", 10));
console.log(simpleHash("dog", 10));
Try it Yourself →
Common Hashing Techniques
The simplest approach is the division method — just take the key's character codes, add them up, and modulo by the table size. It's fast but not great at spreading things out evenly.
Multiplication hashing multiplies by a magic constant (like 0.6180339887) and takes the fractional part. It tends to distribute values more uniformly than division.
In practice, most languages use more sophisticated algorithms. JavaScript's object keys go through their own internal hashing, and you rarely need to write your own hash function unless you're building something from scratch.
function multiplicationHash(key, size) {
let hash = 0;
const A = 0.6180339887;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
const product = hash * A;
const fraction = product - Math.floor(product);
return Math.floor(fraction * size);
}
console.log(multiplicationHash("hello", 100));
console.log(multiplicationHash("world", 100));
Try it Yourself →