JavaScriptFundamental (ES6), part 1
Why use a Map instead of an object in JavaScript
62 Why a plain object is a poor Map
fairUse a plain object as a lookup table and find the four ways it lets you down: inherited keys answer for keys you never set, every key is stringified so two objects collide, a key called hasOwnProperty breaks the usual check, and __proto__ refuses to be stored. Show what a Map and Object.create(null) do instead.
Stuck? Three hints, smallest first
- 1. An empty object already has
toString,constructorand more through its prototype. - 2. Object keys are strings, so any object key becomes
"[object Object]". - 3.
Object.hasOwn(obj, key)andObject.create(null)are the two repairs; a Map avoids the problem entirely.
const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };
const store = {};
const inheritedHit = ['toString' in store, typeof store.toString];
const mapMiss = new Map().has('toString');
store[1] = 'a number key';
const stringifiedKey = [Object.keys(store), store['1'] === store[1]];
const collisions = (() => {
const o = {};
o[{ id: 1 }] = 'first';
o[{ id: 2 }] = 'second'; // the same key as above
return [Object.keys(o), o[{ id: 99 }]];
})();
const shadowed = { hasOwnProperty: 'not a function at all' };
const brokenCheck = attempt(() => shadowed.hasOwnProperty('x'));
const properCheck = Object.hasOwn(shadowed, 'hasOwnProperty');
const protoWrite = {};
protoWrite.__proto__ = 'ignored'; // silently not stored
const protoKeys = Object.keys(protoWrite);
const mapStoresIt = new Map().set('__proto__', 'stored').get('__proto__');
const bare = Object.create(null);
const bareBefore = ['toString' in bare, typeof bare.hasOwnProperty];
bare.toString = 'now just data'; // a key like any other here
const bareLookup = [...bareBefore, bare.toString];
const counts = [Object.keys({ a: 1, b: 2 }).length, new Map([['a', 1], ['b', 2]]).size];
console.log('inherited :', inheritedHit, '| a Map:', mapMiss);
console.log('key types :', stringifiedKey);
console.log('collision :', collisions);
console.log('shadowed :', brokenCheck, '| Object.hasOwn:', properCheck);
console.log('__proto__ :', protoKeys, '| a Map:', mapStoresIt);
console.log('null proto:', bareLookup, '| counts:', counts);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an empty object already answers yes for keys you never set', inheritedHit, [true, 'function']);
test('an empty Map has nothing in it whatsoever', mapMiss, false);
test('an object key is converted to a string on the way in', stringifiedKey, [['1'], true]);
test('so two different objects become one key, and any third object reads it', collisions, [['[object Object]'], 'second']);
test('a key called hasOwnProperty breaks the usual own-key check', brokenCheck, 'TypeError');
test('while Object.hasOwn cannot be shadowed', properCheck, true);
test('assigning __proto__ stores nothing, where a Map simply stores it', [protoKeys, mapStoresIt], [[], 'stored']);
test('Object.create(null) drops the inherited keys, and the helper methods with them', bareLookup, [false, 'undefined', 'now just data']);
test('size is a property on a Map and a computation on an object', counts, [2, 2]);
Every one of these is a real bug someone has shipped. A user called constructor passes an if (users[name]) check that should have failed. An id read from JSON as the number 1 and later as the string '1' hit the same slot, which is lucky until it is not. A cache keyed by request objects collapses into one entry called [object Object], so every lookup returns the last thing written. And obj[userInput] = value with userInput of '__proto__' is the shape of a real class of vulnerability.
Use a Map when the keys are data: arbitrary key types, no prototype, insertion order, a size, and cheap delete. Use an object when the keys are known at authoring time, which is what objects are actually for. Object.create(null) is the middle option — no inherited keys at all — at the cost of losing toString, hasOwnProperty and friends, so it prints awkwardly in a debugger.
A WeakMap is the same idea with three deliberate restrictions: keys must be objects, they are held weakly so an entry vanishes when nothing else references its key, and it is neither iterable nor countable — no size, no keys(). That is the point. It is for attaching data to objects you do not own, such as metadata for a DOM node, without keeping them alive for ever. If you can list what is in it, you can keep it alive, so the API refuses to let you.