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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.MIME Type LookupResolve a file extension, file name, or MIME type to its media type, category, and related extensions using a local reference table.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.