In modern JavaScript, Map is generally the best general-purpose data structure for storing key-value pairs when keys are dynamic, frequently added or deleted, non-string/object/symbol values, or when you need .size, guaranteed insertion-order iteration, and no Object.prototype key collisions—whereas a plain object ({}) is best for static/known string-keyed records, JSON serialization (JSON.stringify), or structured schema fields (or Object.create(null) when using dynamic string keys on an object without prototype pollution).
1. Using Map for Dynamic Keys, Frequent Updates, and Non-String Keys
Use new Map() whenever keys are added/removed dynamically at runtime, values or keys aren’t plain strings (such as DOM elements, objects, numbers, or NaN), or you want clean .set(), .get(), .has(), .delete(), and .size ergonomics:
// Manage dynamic key-value pairs safely using a Map
function createKeyValueStore(initialEntries = []) {
if (!Array.isArray(initialEntries)) {
throw new TypeError("Expected initialEntries to be an array of [key, value] pairs.");
}
const store = new Map();
for (const entry of initialEntries) {
if (!Array.isArray(entry) || entry.length < 2) {
throw new TypeError("Each entry in initialEntries must be a [key, value] tuple.");
}
store.set(entry[0], entry[1]);
}
return {
set(key, value) {
store.set(key, value);
return this;
},
get(key, fallback = undefined) {
return store.has(key) ? store.get(key) : fallback;
},
delete(key) {
return store.delete(key);
},
size() {
return store.size;
},
entries() {
return Array.from(store.entries());
}
};
}
// Example usage:
try {
const cache = createKeyValueStore([["retryLimit", 3]]);
cache.set("timeoutMs", 2500);
console.log(cache.get("timeoutMs")); // 2500
console.log(cache.size()); // 2
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
- No prototype collision risk: Keys like
"constructor","toString", or"__proto__"work safely in aMapwithout touchingObject.prototype. - Matches
NaNkeys cleanly:MapusesSameValueZero, soNaNcan be stored and retrieved as a key.
2. Plain Objects ({}) vs. Object.create(null) for Record Data
Use a plain object ({}) for fixed, known fields or data that must serialize directly to JSON, and use Object.create(null) (or Object.hasOwn(obj, key)) when treating an object as a dynamic string dictionary so inherited prototype properties never interfere:
// Safely read an own string property from an object without prototype collisions
function readOwnField(record, key, fallback = undefined) {
if (record === null || typeof record !== "object" || Array.isArray(record)) {
throw new TypeError("Expected record to be a non-null plain object.");
}
if (typeof key !== "string") {
throw new TypeError("Expected key to be a string.");
}
return Object.hasOwn(record, key) ? record[key] : fallback;
}
// Example usage:
const configRecord = { host: "localhost", port: 8080 };
console.log(readOwnField(configRecord, "port")); // 8080
console.log(readOwnField(configRecord, "toString")); // undefined (safe from Object.prototype)
- JSON compatibility:
JSON.stringify(new Map(...))produces{}by default, whereas plain objects serialize directly to JSON objects. - Avoid
obj[key]on untrusted keys withoutObject.hasOwn(): Readingrecord["toString"]directly returns a function unless guarded withObject.hasOwn().
3. WeakMap for Object-Keyed Metadata Without Memory Leaks
When keys are objects and you want automatic garbage collection once those objects are no longer referenced elsewhere in the program, use a WeakMap rather than a Map (note that WeakMap is not iterable and has no .size):
// Attach private/ephemeral metadata to object instances without preventing GC
function createObjectMetadataStore() {
const metadataByObject = new WeakMap();
return {
attach(target, meta) {
if (target === null || (typeof target !== "object" && typeof target !== "function")) {
throw new TypeError("WeakMap keys must be non-null objects or functions.");
}
metadataByObject.set(target, meta);
},
read(target) {
if (target === null || (typeof target !== "object" && typeof target !== "function")) {
return undefined;
}
return metadataByObject.get(target);
}
};
}
// Example usage:
const domMeta = createObjectMetadataStore();
const fakeNode = { id: "node-1" };
domMeta.attach(fakeNode, { initialized: true });
console.log(domMeta.read(fakeNode)); // { initialized: true }
- Prevents retention leaks: Once
fakeNodegoes out of scope elsewhere, itsWeakMapentry becomes eligible for garbage collection. - Non-enumerable by design: Use
Mapinstead whenever you need to iterate keys/entries or inspect.size.
