Skip to content

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.

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
FeatureDescription
Key typesAny value (objects, functions, primitives)
OrderMaintains insertion order
Size.size property for quick length check
PerformanceOptimized for frequent additions/deletions
IterationDirectly iterable with for...of
const map = new Map();
const mapFromIterable = new Map([
["key1", "value1"],
["key2", "value2"],
]);
  • 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).
  • NaN can be used as a key (only one NaN key).
// Creating a new Map
const map = new Map();
// Using objects as keys
const 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 keys
map.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 iterable
const fromArray = new Map([
["a", 1],
["b", 2],
["c", 3],
]);
console.log(fromArray.get("a")); // 1
console.log(fromArray.get("b")); // 2
console.log(fromArray.get("c")); // 3
// Map size
console.log(map.size); // Number of entries