Learn the concept
Data Structures
Use Map when you need non-string keys, frequent additions/deletions, or need to preserve insertion order with a size property. Use Set when you need unique values, fast lookups with has(), or need to remove duplicates from an array.
Map vs Object:
| Feature | Map | Object |
|---------|-----|--------|
| Key types | Any value (objects, functions, primitives) | Strings and Symbols only |
| Order | Guaranteed insertion order | Mostly ordered (with caveats) |
| Size | map.size property | Object.keys(obj).length |
| Iteration | Directly iterable (for...of) | Need Object.keys/values/entries |
| Performance | Better for frequent add/delete | Better for static data |
| Prototype | No inherited keys | Has prototype chain keys |
Set vs Array:
| Feature | Set | Array |
|---------|-----|-------|
| Uniqueness | All values unique | Allows duplicates |
| Lookup | has() is O(1) | includes() is O(n) |
| Delete | delete() is O(1) | splice() is O(n) |
| Order | Insertion order | Index-based order |
| Indexing | No index access | arr[i] |
// Non-string keys
const cache = new Map();
const userObj = { id: 1 };
cache.set(userObj, 'cached data'); // object as key
cache.get(userObj); // 'cached data'
// DOM element metadata
const elementData = new Map();
const button = document.querySelector('button');
elementData.set(button, { clicks: 0, lastClicked: null });
// Frequent operations with size tracking
const sessions = new Map();
sessions.set('abc123', { user: 'Alice' });
sessions.delete('abc123');
console.log(sessions.size); // 0
// Iteration
const scores = new Map([['Alice', 95], ['Bob', 87]]);
for (const [name, score] of scores) {
console.log(`${name}: ${score}`);
}
// Convert to/from object
const obj = Object.fromEntries(scores);
const map = new Map(Object.entries(obj));Using Map with object keys to cache computed results for specific inputs without stringifying keys
Using Set to remove duplicate items from arrays or track unique values like visited pages or selected IDs
Using Set for fast O(1) membership checks on allowed roles, feature flags, or whitelisted values
Build a least-recently-used cache using Map's insertion order guarantee and size tracking
Build a tagging system using Set for unique tags with native union/intersection methods for filtering