JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Data Structures

javascript
mid
data-structures

When should you use Map and Set instead of plain objects and arrays?

map
set
data-structures
collections
es6
Quick Answer

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.

Detailed Explanation

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] |

Code Examples

Map use casesJavaScript
// 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));

Real-World Applications

Use Cases

Caching

Using Map with object keys to cache computed results for specific inputs without stringifying keys

Deduplication

Using Set to remove duplicate items from arrays or track unique values like visited pages or selected IDs

Permission Systems

Using Set for fast O(1) membership checks on allowed roles, feature flags, or whitelisted values

Mini Projects

LRU Cache

beginner

Build a least-recently-used cache using Map's insertion order guarantee and size tracking

Tag Manager

intermediate

Build a tagging system using Set for unique tags with native union/intersection methods for filtering

Industry Examples

WeakMap

DOM frameworks use WeakMap to associate metadata with elements without preventing garbage collection

D3.js

Uses Map and Set extensively for data joins, grouping, and unique value tracking in visualizations

Resources

MDN - Map

docs

MDN - Set

docs

JavaScript.info - Map and Set

article

Related Questions

What is the difference between map(), filter(), and reduce() array methods?

junior
arrays
Previous
What is the difference between ES Modules (ESM) and CommonJS (CJS)?
Next
What are call, apply, and bind and how do they differ?
PrevNext