patternjavascriptModerate
Map vs Object for dictionary-like data structures
Viewed 0 times
Map: ES2015
Mapdictionaryobject vs mapprototype pollutionnon-string keys
Problem
Plain objects used as dictionaries have inherited prototype keys, string-coerced keys, and unpredictable iteration order for numeric keys.
Solution
Use Map when keys are not strings, insertion order must be preserved for all keys, you need .size, or you are frequently adding/deleting keys.
const map = new Map();
map.set(objRef, 'value'); // non-string key
map.set(42, 'numeric key');
map.size; // 2
// No prototype pollution risk
map.set('constructor', 'safe');
const map = new Map();
map.set(objRef, 'value'); // non-string key
map.set(42, 'numeric key');
map.size; // 2
// No prototype pollution risk
map.set('constructor', 'safe');
Why
Map uses SameValueZero comparison for keys (handles NaN), guarantees insertion order for all key types, and is optimised for frequent add/delete operations.
Gotchas
- Map cannot be directly JSON.stringify'd — convert to [...map.entries()] first
- Use map.has(key) to check membership — map.get() returns undefined for both missing keys and keys set to undefined
- Object.create(null) produces a prototype-free object — a lighter alternative for string-only keys
- Map.get() returning undefined is ambiguous — distinguish with has()
Code Snippets
Map vs Object key ordering
// Object — numeric keys are sorted first
const obj = { 2: 'b', 1: 'a', name: 'c' };
Object.keys(obj); // ['1', '2', 'name']
// Map — insertion order always preserved
const map = new Map([[2, 'b'], [1, 'a'], ['name', 'c']]);
[...map.keys()]; // [2, 1, 'name']
// Serialise
JSON.stringify([...map.entries()]);Revisions (0)
No revisions yet.