JavaScript Map, Set, WeakMap & WeakSet: High-Performance Keyed Collections

Prior to ES6, developers were forced to abuse plain Objects as dictionaries and Arrays as sets. Map and Set introduced dedicated, optimized, highly performant keyed collections into the ECMAScript standard.

1. The Map Collection (Key-Value Pairs)

Unlike plain objects whose keys must be strings or symbols, a Map allows ANY data type as a key (including objects and functions):

const userPermissions = new Map();

const userVikram = { id: 101, name: "Vikram" };
const userPooja = { id: 102, name: "Pooja" };

// Using OBJECTS as keys!
userPermissions.set(userVikram, "SuperAdmin");
userPermissions.set(userPooja, "Editor");

console.log(userPermissions.get(userVikram)); // "SuperAdmin"
console.log(userPermissions.size);              // 2
console.log(userPermissions.has(userPooja));    // true

2. The Set Collection (Unique Values Only)

A Set is a collection of unique values; duplicates are rejected automatically:

const studentIds = new Set();
studentIds.add(101);
studentIds.add(102);
studentIds.add(101); // DUPLICATE! Silently ignored.

console.log(studentIds.size); // 2

// INDUSTRY TRICK: Array Deduplication in ONE line!
const rawTags = ["javascript", "coding", "web", "javascript", "web"];
const uniqueTags = [...new Set(rawTags)];
console.log(uniqueTags); // ["javascript", "coding", "web"]

3. WeakMap & WeakSet (Memory-Leak Free)

WeakMap and WeakSet hold weak references to object keys. When the object key loses all other references, the JavaScript garbage collector automatically purges it from memory:

let sessionData = new WeakMap();
let tempUser = { token: "xyz-789" };

sessionData.set(tempUser, { loginTime: Date.now() });

// When tempUser is cleared:
tempUser = null; 
// The entry in sessionData will be cleanly garbage-collected automatically!

University Exam Corner (BCA Examination Notes)

Exam Comparison Table: "Map vs Object in Modern JavaScript."

FeatureMapPlain Object
Key TypesAny data type (Objects, primitives)String or Symbol only
Size Checkmap.size (O(1))Object.keys(obj).length (O(N))
Iteration OrderGuaranteed insertion orderArbitrary / complex numeric sort

Next Step

Congratulations on completing Tier 3: Data Structures & Objects! Now let us connect JavaScript with HTML web pages. Proceed to Tier 4: JavaScript DOM Architecture & Element Selectors →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!