Map
The Map object is a collection of key-value pairs where keys can be of any type (including objects, functions, and primitives). Unlike plain objects, Maps preserve insertion order and provide better performance for frequent additions and deletions.
What Problem Does Map Solve?
Section titled “What Problem Does Map Solve?”Traditional objects have limitations:
- Keys are always converted to strings
- Keys must be unique but type coercion causes issues
- No built-in size property
- Iteration order is not guaranteed
- Prototype inheritance can cause collisions
Key Characteristics
Section titled “Key Characteristics”| Feature | Description |
|---|---|
| Key types | Any value (objects, functions, primitives) |
| Order | Maintains insertion order |
| Size | .size property for quick length check |
| Performance | Optimized for frequent additions/deletions |
| Iteration | Directly iterable with for...of |
Syntax
Section titled “Syntax”const map = new Map();const mapFromIterable = new Map([ ["key1", "value1"], ["key2", "value2"],]);Key Points
Section titled “Key Points”- Maps can use any value as a key (objects, functions, NaN).
- Keys are compared using the SameValueZero algorithm.
- Insertion order is preserved during iteration.
- Maps are iterable by default (returns
[key, value]pairs). NaNcan be used as a key (only one NaN key).
Example Code
Section titled “Example Code”// Creating a new Mapconst map = new Map();
// Using objects as keysconst user1 = { id: 1 };const user2 = { id: 2 };
map.set(user1, "Alice");map.set(user2, "Bob");
console.log(map.get(user1)); // 'Alice'console.log(map.get(user2)); // 'Bob'
// Using other primitives as keysmap.set(42, "The answer");map.set(true, "Boolean key");map.set("name", "String key");map.set(NaN, "Not a number");
console.log(map.get(42)); // 'The answer'console.log(map.get(true)); // 'Boolean key'console.log(map.get(NaN)); // 'Not a number'
// Creating a Map from an iterableconst fromArray = new Map([ ["a", 1], ["b", 2], ["c", 3],]);
console.log(fromArray.get("a")); // 1console.log(fromArray.get("b")); // 2console.log(fromArray.get("c")); // 3
// Map sizeconsole.log(map.size); // Number of entries