Keyed collections in JavaScript mainly refer to:
MapWeakMapSetWeakSetThey are useful when plain objects or arrays are not the best fit.
MapMap stores key-value pairs and allows keys of any type.
const map = new Map();
map.set("name", "Tom");map.set(1, "one");map.set(true, "yes");
console.log(map.get("name")); // "Tom"console.log(map.has(1)); // trueconsole.log(map.size); // 3ObjectMap is usually a better choice when:
WeakMapWeakMap only accepts objects as keys.
const wm = new WeakMap();const user = {};
wm.set(user, { cached: true });console.log(wm.get(user));Important characteristics:
WeakMap is commonly used for:
SetSet stores unique values.
const set = new Set([1, 2, 2, 3]);console.log(set); // Set {1, 2, 3}
set.add(4);set.delete(2);console.log(set.has(1)); // trueconst arr = [1, 2, 2, 3, 3];const unique = [...new Set(arr)];const a = new Set([1, 2, 3]);const b = new Set([3, 4, 5]);
const union = new Set([...a, ...b]);const intersection = new Set([...a].filter((x) => b.has(x)));const difference = new Set([...a].filter((x) => !b.has(x)));Set is useful when:
has checks matterWeakSetWeakSet is similar to WeakMap, but it stores only objects and no values.
const weakSet = new WeakSet();const obj = {};
weakSet.add(obj);console.log(weakSet.has(obj)); // trueIt is often used to mark objects:
SameValueZeroMap and Set use the SameValueZero rule for equality.
That means:
NaN is considered equal to NaN0 and -0 are treated as equalMap when keys are not naturally object property namesSet when you need uniquenessWeakMap or WeakSet when keys should not prevent garbage collectionMapSetWeakMapWeakSet