Map Versus Object For Lookup Tables

Compare Map and plain-object lookup semantics: object keys stringify, Map keys keep identity, and size plus delete behave predictably for dynamic data.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// Object keys are strings/symbols; Map keys keep any value, including objects.
const userKey = { id: 1 };
const byObject = {};
byObject[userKey] = 'alice'; // key coerced to the string "[object Object]"
console.log('object key:', Object.keys(byObject)[0]);

const byMap = new Map();
byMap.set(userKey, 'alice');
console.log('map key identity:', byMap.get(userKey), byMap.get({ id: 1 }));

// size and deletion semantics differ too
byMap.set('session', 'active');
console.log('map size:', byMap.size, 'has session:', byMap.has('session'));
byMap.delete('session');
console.log('after delete:', byMap.size);

// Objects fit fixed-shape records; Map fits dynamic or non-string keys
console.log('remaining keys:', [...byMap.keys()].length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

object key: [object Object]
map key identity: alice undefined
map size: 2 has session: true
after delete: 1
remaining keys: 1

How it works

The demo data lives in module-level bindings: userKey, byObject, byMap.

The top-level object literal pins id as plain values — no derivation, no imports behind them.

Watch out for

  • The environment needs no preparation beyond having the interpreter or compiler.

Using it

Each run prints the 5 labeled blocks object key:, map key identity:, map size:, after delete:, remaining keys: in source order.

Key statements

const byMap = new Map();

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `userKey`, `byObject`, `byMap`.