DEV Community

Cover image for Every JavaScript Object is a Hash Table — Here is What is Actually Happening Inside Your Curly Braces
Amar Gul
Amar Gul

Posted on

Every JavaScript Object is a Hash Table — Here is What is Actually Happening Inside Your Curly Braces

Every time you write this:

\javascript
const user = {
name: "Amar",
role: "Senior Dev"
};
\
\

A hash table is running under the hood.

What Actually Happens

When you set user.name = "Amar" — the
key "name" passes through a hash function:

\javascript
function hashFunction(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i)) % BUCKET_COUNT;
}
return hash;
}
// hashFunction("name") → 3
// Value stored in bucket 3
\
\

Why Lookup is O(1)

When you read user.name:

  1. Run hashFunction("name") → 3
  2. Go directly to bucket 3
  3. Return value

No searching. No comparing. No looping.
Direct access regardless of object size.

The Collision Problem

Two different keys can produce the same
bucket number. This is called a collision.

\javascript
hashFunction("name") → 3
hashFunction("role") → 3 // same bucket!
\
\

JavaScript handles this through chaining
— each bucket holds a linked list of
all key-value pairs that hash to that
index.

Watch It Live

What's Next

Dynamic Programming — turning O(2ⁿ)
problems into O(n) with memoization.

Subscribe to AlgoCanvas:
👉 youtube.com/@AlgoCanvas

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Your hash function will fall flat on it's face with Symbol keys