Map Keys Match By Reference Identity

Show that Map matches object keys by reference identity, so an equal-shaped clone misses, while primitive keys keep plain value-equality matching.

JavascriptData Integrity

Code

javascriptsnippet
24 lines
const sessions = new Map();

const alice = { userId: 7, device: 'macbook' };
sessions.set(alice, 'token-a');

// 同一个对象引用作为 key:命中
console.log('same reference:', sessions.get(alice));

// 形状完全相同的新对象:引用不同,Map 查不到(对象键不做结构相等比较)
const impostor = { userId: 7, device: 'macbook' };
console.log('clone lookup:', sessions.get(impostor));

// get/delete 按引用匹配:就地改字段不影响身份,失败的查找也不会新增条目
alice.device = 'linux';
console.log('after mutation:', sessions.get(alice));
console.log('size:', sessions.size);

// 原始值 key 仍按值相等比较
const scores = new Map([
  ['alice', 91],
  [42, 'answer'],
]);
console.log('string key:', scores.get('alice'));
console.log('number key:', scores.get(42));

Inside the snippet

Top-level bindings sessions, alice, impostor, scores hold the demo state — nothing sits inside a function scope.

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

Using it

The run emits 6 labeled sections — same reference:, clone lookup:, after mutation:, size:, string key:, number key: — one per step.

Key statements

const sessions = new Map();
const scores = new Map([
  ['alice', 91],
  [42, 'answer'],
]);

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `sessions`, `alice`, `impostor`.