Dynamic dictionaries
Keys arrive dynamically or come from external input.
JS Puzzles · Const
Map is a keyed collection like Object, but it accepts keys of any type, including objects, and provides convenient methods plus size. Use it for dynamic keyed data; use Object when the shape and string-like keys are known in advance.
Use Map for a keyed collection when keys are not known in advance or may be objects and other non-string values. Use a plain object when the data shape is known and its property keys are strings or symbols.
new Map([iterable])| Name | Type | Description |
|---|---|---|
iterable | Iterable<readonly [any, any]> | The iterable of key-value pairs used to initialize the Map; omitted when creating an empty Map. |
A Map object containing the supplied key-value pairs.
const objectKey = { id: 1 };
const map = new Map([[objectKey, "value"]]);
console.log(map.get(objectKey)); // "value"
console.log(map.size); // 1
console.log(Object.keys({ a: 1 })); // ["a"]Map preserves an object key as an object and exposes size directly; Object.keys returns an array for an object.
Keys arrive dynamically or come from external input.
Objects, functions, or other non-string values identify entries.
The collection needs direct size access and insertion-order iteration.
Map is a keyed collection like Object, but its keys may have any type, including objects. A plain Object uses string or symbol property keys, while Map also provides convenient methods and size.
Follow-up: When should an Object be preferred? Prefer it when the shape is known ahead of time and all keys can be represented as strings.
Map keys are not converted to strings, so object references can be used directly as keys. The same object reference must be supplied to retrieve the associated value.
Follow-up: What happens with an object key in Object? It is converted to a string property key, so separate object keys do not remain distinct.
Map has methods such as set(), get(), and has(), plus the size property. Its entries iterate in insertion order, whereas Object uses Object.keys(), Object.values(), or Object.entries() for comparable operations.
Follow-up: How can a plain object be converted to a Map? Pass Object.entries(obj) to the Map constructor.
MapObjectObject.entries()map.set(key, value)map.get(key)map.has(key)map.delete(key)map.clear()