Map and Set
Map and Set
Section titled โMap and SetโWhat it is
Section titled โWhat it isโMap and Set are new collection types introduced in ES6 (2015). Map stores key-value pairs with any type of key. Set stores unique values of any type.
Before this feature
Section titled โBefore this featureโUsed objects or arrays with manual uniqueness checks:
// Object as map (keys must be strings)const map = {};map["key1"] = "value1";map["key2"] = "value2";
// Can't use objects as keysconst obj1 = { id: 1 };map[obj1] = "value"; // Key becomes "[object Object]"
// Array for unique values (manual checking)const unique = [];function addUnique(value) { if (!unique.includes(value)) { unique.push(value); }}After this feature
Section titled โAfter this featureโMap and Set provide purpose-built collections:
// Map - key-value pairs with any key typeconst map = new Map();
map.set("name", "Alice");map.set(42, "The Answer");map.set({ id: 1 }, "object value");map.set(true, "boolean key");
console.log(map.get("name")); // "Alice"console.log(map.has(42)); // trueconsole.log(map.size); // 4
map.delete(42);map.clear(); // remove all
// Chainingmap.set("a", 1).set("b", 2).set("c", 3);
// Iterationmap.forEach((value, key) => { console.log(`${key}: ${value}`);});
for (const [key, value] of map) { console.log(key, value);}
// Set - unique valuesconst set = new Set();
set.add(1);set.add(2);set.add(2); // Ignored - already existsset.add(3);
console.log(set.size); // 3console.log(set.has(2)); // true
set.delete(2);set.clear(); // remove all
// Remove duplicates from arrayconst arr = [1, 2, 2, 3, 3, 4];const unique = [...new Set(arr)]; // [1, 2, 3, 4]
// Set iterationfor (const value of set) { console.log(value);}
set.forEach(value => console.log(value));
// Initialize with valuesconst numbers = new Set([1, 2, 3, 4, 5]);const words = new Map([ ["hello", "greeting"], ["goodbye", "farewell"]]);Why this is better
Section titled โWhy this is betterโ- Any key type: Map accepts any value as key (objects, functions, etc.)
- Unique values: Set automatically handles uniqueness
- Size property: Easy to get count
- Iteration: Built-in iteration support
- Performance: Better performance for add/delete/has operations
Key notes / edge cases
Section titled โKey notes / edge casesโ- Map keys compared by SameValueZero (like
===butNaN === NaN) - Set values are also compared by SameValueZero
- Insertion order is preserved
- WeakMap and WeakSet variants exist for garbage collection
- Objects used as keys must be same reference
// NaN handlingconst set = new Set();set.add(NaN);set.add(NaN); // Ignored - considered sameconsole.log(set.size); // 1
// Object key comparison (by reference)const map = new Map();map.set({ id: 1 }, "value1");map.set({ id: 1 }, "value2"); // Different object!console.log(map.size); // 2
const key = { id: 1 };map.set(key, "value");console.log(map.get(key)); // "value" - same reference
// Convert Map to Objectconst map = new Map([["a", 1], ["b", 2]]);const obj = Object.fromEntries(map);
// Convert Object to Mapconst obj = { a: 1, b: 2 };const map = new Map(Object.entries(obj));Quick practice
Section titled โQuick practiceโ-
Remove duplicates from
[1, 2, 2, 3, 3, 4]using SetAnswer
const unique = [...new Set([1, 2, 2, 3, 3, 4])]; -
Create a Map with object keys
Answer
const map = new Map();const obj1 = { id: 1 };const obj2 = { id: 2 };map.set(obj1, "value1");map.set(obj2, "value2"); -
Whatโs the difference between Map and Object?
Answer
Map: any type of key, preserves insertion order, has size property, better performance for frequent add/delete. Object: string/symbol keys only, size via Object.keys(obj).length.