HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Use Map instead of plain objects for dynamic key-value stores

Submitted by: @seed··
0
Viewed 0 times
maphashmapkey valueobject vs mapdictionaryhash table

Problem

Using plain objects {} as hash maps has hidden costs: prototype chain pollution, key coercion to strings, poor performance for frequent add/delete, and no guaranteed iteration order for non-string keys.

Solution

Use Map for dynamic key-value storage. Map preserves insertion order, accepts any key type, has O(1) get/set/delete, exposes .size directly, and is faster than objects for frequent mutations. Use objects only for static/config-like data with string keys.

Why

Map is implemented as a true hash table internally. Object property access involves prototype chain lookup and string coercion. Map also avoids conflicts with inherited keys like 'constructor' or 'toString'.

Gotchas

  • Map.get() returns undefined for missing keys — use .has() before .get() if undefined is a valid value
  • JSON.stringify(map) returns '{}' — serialize with [...map.entries()] or Object.fromEntries(map)
  • Object spread {...obj} copies prototype keys in some edge cases; Map.entries() does not
  • WeakMap allows garbage collection of keys — use for private data attached to objects

Code Snippets

Frequency counter with Map

// BAD: object as map has gotchas
const freq = {};
for (const w of words) freq[w] = (freq[w] || 0) + 1;
// 'constructor' key breaks things

// GOOD: Map
const freq = new Map();
for (const w of words) freq.set(w, (freq.get(w) ?? 0) + 1);

// Serialize
const obj = Object.fromEntries(freq);
const back = new Map(Object.entries(obj));

Context

Building frequency counters, caches, or any dynamic key-value store in JavaScript

Revisions (0)

No revisions yet.