JavaScript Map, Set, WeakMap and WeakSet Explained with Examples

Objects and arrays cover most needs, but two jobs come up again and again where they are clumsy: storing values by a key that is not a simple string, and keeping a collection of unique values. JavaScript has dedicated collections for these, Map and Set, plus memory-friendly versions, WeakMap and WeakSet. In this lesson you will learn all four, when to choose them over plain objects and arrays, and the new set operations (union, intersection, difference) that make comparing expected and actual data in tests a one-liner.

Advertisement

📖 What You’ll Learn: creating and using Map, Map versus plain objects, iterating a Map, counting and grouping with Map, creating and using Set, removing duplicates, set operations (union, intersection, difference, symmetricDifference, isSubsetOf), WeakMap and WeakSet and garbage collection, converting between collections, and comparing expected and actual values in tests.


🗺️ Map: Key–Value Pairs with Any Key Type

Definition: a Map is a collection of key–value pairs where the keys can be any value: strings, numbers, booleans, objects or functions. It remembers insertion order and has a size.

📄 map.js

const statusText = new Map([
  [200, "OK"],
  [404, "Not Found"],
]);

statusText.set(500, "Server Error");      // add or update
console.log(statusText.get(404));         // read
console.log(statusText.get(418));         // missing key: undefined
console.log(statusText.has(200), statusText.size);

statusText.delete(404);
console.log([...statusText.keys()], [...statusText.values()]);

console.log(new Map().set("a", 1).set("b", 2));   // set returns the map, so calls chain

⌨️ Terminal

node map.js

🖥️ Output

Not Found
undefined
true 3
[ 200, 500 ] [ 'OK', 'Server Error' ]
Map(2) { 'a' => 1, 'b' => 2 }
Map method / propertyDoes
new Map(entries)Create, optionally from [key, value] pairs
set(key, value)Add or update; returns the map
get(key)Read; undefined if missing
has(key) / delete(key)Check / remove (both return booleans)
sizeNumber of entries
clear()Remove everything
keys(), values(), entries(), forEach()Iterate in insertion order

Objects as keys

A plain object converts every key to a string, so two different objects collide on the key "[object Object]". A Map keeps them apart:

📄 object-keys.js

const pageA = { url: "/login" };
const pageB = { url: "/cart" };

const asObject = {};
asObject[pageA] = "visited A";
asObject[pageB] = "visited B";
console.log(asObject);                       // one key: "[object Object]"

const asMap = new Map();
asMap.set(pageA, "visited A").set(pageB, "visited B");
console.log(asMap.get(pageA), "|", asMap.get(pageB), "|", asMap.size);

⌨️ Terminal

node object-keys.js

🖥️ Output

{ '[object Object]': 'visited B' }
visited A | visited B | 2

⚖️ Map vs Plain Object

MapPlain object
Key typesAny valueStrings and symbols only
OrderInsertion orderInteger-like keys first, then insertion order
Sizemap.sizeObject.keys(obj).length
IterationDirectly iterable (for...of)Needs Object.entries
Accidental keysNoneInherited keys like toString, __proto__
JSONNot supported directly (convert first)Native
Best forDynamic keys, frequent add/remove, counting, cachesFixed records, config, JSON data

📄 map-vs-object.js

const counts = {};
for (const word of ["constructor", "toString", "qa"]) {
  counts[word] = (counts[word] || 0) + 1;
}
console.log(counts);      // inherited methods break the counting!

const safeCounts = new Map();
for (const word of ["constructor", "toString", "qa"]) {
  safeCounts.set(word, (safeCounts.get(word) ?? 0) + 1);
}
console.log(safeCounts);

⌨️ Terminal

node map-vs-object.js

🖥️ Output

{
  constructor: 'function Object() { [native code] }1',
  toString: 'function toString() { [native code] }1',
  qa: 1
}
Map(3) { 'constructor' => 1, 'toString' => 1, 'qa' => 1 }

Counting with a plain object went wrong because counts.constructor and counts.toString already exist (inherited functions). A Map has no such hidden keys.


Advertisement

🔁 Iterating, Counting and Converting Maps

📄 iterate-map.js

const durations = new Map([
  ["login", 820],
  ["search", 1430],
  ["cart", 610],
]);

for (const [test, ms] of durations) {
  console.log(`${test.padEnd(7)} ${ms} ms`);
}

const slowest = [...durations].reduce((a, b) => (b[1] > a[1] ? b : a));
console.log("slowest:", slowest);

const asObject = Object.fromEntries(durations);          // Map -> object (e.g. for JSON)
const backToMap = new Map(Object.entries(asObject));     // object -> Map
console.log(JSON.stringify(asObject), backToMap.get("cart"));

const sortedByTime = new Map([...durations].sort((a, b) => a[1] - b[1]));
console.log([...sortedByTime.keys()]);

⌨️ Terminal

node iterate-map.js

🖥️ Output

login   820 ms
search  1430 ms
cart    610 ms
slowest: [ 'search', 1430 ]
{"login":820,"search":1430,"cart":610} 610
[ 'cart', 'login', 'search' ]

Map.groupBy(items, fn) (ES2024) groups an array into a Map, the Map version of Object.groupBy:

📄 map-groupby.js

const results = [{ t: "a", ok: true }, { t: "b", ok: false }, { t: "c", ok: true }];
const grouped = Map.groupBy(results, (r) => r.ok);    // boolean keys are fine in a Map
console.log(grouped.get(true).map((r) => r.t), grouped.get(false).map((r) => r.t));

⌨️ Terminal

node map-groupby.js

🖥️ Output

[ 'a', 'c' ] [ 'b' ]

🎯 Set: A Collection of Unique Values

Definition: a Set stores unique values of any type. Adding a value that is already there does nothing. Like Map, it keeps insertion order and has size.

📄 set.js

const tags = new Set(["smoke", "login", "smoke"]);
console.log(tags, tags.size);

tags.add("regression").add("login");    // "login" is already there
console.log(tags.has("regression"), tags.has("api"));
tags.delete("smoke");
console.log([...tags]);

const ids = [3, 1, 3, 2, 1, 2];
console.log([...new Set(ids)]);          // remove duplicates
console.log(new Set("mississippi").size); // unique letters

⌨️ Terminal

node set.js

🖥️ Output

Set(2) { 'smoke', 'login' } 2
true false
[ 'login', 'regression' ]
[ 3, 1, 2 ]
4

⚠️ Watch out: Sets compare objects by reference, like ===. Two separate objects with the same contents are both kept: new Set([{ id: 1 }, { id: 1 }]).size is 2. To deduplicate objects, use a Map keyed by an ID.

📄 set-objects.js

const users = [{ id: 1, n: "Asha" }, { id: 2, n: "Ravi" }, { id: 1, n: "Asha" }];
console.log(new Set(users).size);
const unique = [...new Map(users.map((u) => [u.id, u])).values()];
console.log(unique);

⌨️ Terminal

node set-objects.js

🖥️ Output

3
[ { id: 1, n: 'Asha' }, { id: 2, n: 'Ravi' } ]

Advertisement

🔀 Set Operations: Union, Intersection, Difference

ES2025 added set-algebra methods to Set. They return new Sets (or booleans) and leave the originals unchanged. They are available in Node.js 22+ and current browsers:

📄 set-ops.js

const expected = new Set(["Home", "Tutorials", "Practice", "Blog", "Contact"]);
const actual = new Set(["Home", "Tutorials", "Blog", "Jobs"]);

console.log("in both:", [...expected.intersection(actual)]);
console.log("missing:", [...expected.difference(actual)]);
console.log("unexpected:", [...actual.difference(expected)]);
console.log("all:", [...expected.union(actual)]);
console.log("in exactly one:", [...expected.symmetricDifference(actual)]);
console.log(new Set(["Home"]).isSubsetOf(expected), expected.isSupersetOf(actual), expected.isDisjointFrom(new Set(["Login"])));

⌨️ Terminal

node set-ops.js

🖥️ Output

in both: [ 'Home', 'Tutorials', 'Blog' ]
missing: [ 'Practice', 'Contact' ]
unexpected: [ 'Jobs' ]
all: [ 'Home', 'Tutorials', 'Practice', 'Blog', 'Contact', 'Jobs' ]
in exactly one: [ 'Practice', 'Contact', 'Jobs' ]
true false true
MethodReturns
a.union(b)Everything in a or b
a.intersection(b)Only items in both
a.difference(b)Items in a but not in b
a.symmetricDifference(b)Items in exactly one of them
a.isSubsetOf(b) / isSupersetOf / isDisjointFromBooleans

💡 Tip: In older environments, write the same operations with filter: [...a].filter((x) => b.has(x)) for intersection and [...a].filter((x) => !b.has(x)) for difference. set.has is fast, which is why converting an array to a Set first speeds up repeated lookups.


🪶 WeakMap and WeakSet

Definition: a WeakMap is like a Map whose keys must be objects and are held weakly: if nothing else in the program references a key object, it can be garbage-collected, and its entry disappears automatically. A WeakSet is the same idea for a set of objects.

  • Keys (WeakMap) and values (WeakSet) must be objects (or non-registered symbols), not primitives.
  • They are not iterable and have no size, because entries can vanish at any time.
  • Available methods: WeakMap get, set, has, delete; WeakSet add, has, delete.

📄 weak.js

// Attach extra data to objects you do not own, without changing them or leaking memory
const renderCount = new WeakMap();

function render(component) {
  renderCount.set(component, (renderCount.get(component) ?? 0) + 1);
}

const header = { name: "Header" };
render(header);
render(header);
console.log(renderCount.get(header), Object.keys(header));   // the object itself is unchanged

// Track which objects were already processed
const processed = new WeakSet();
function processOnce(obj) {
  if (processed.has(obj)) return "skipped";
  processed.add(obj);
  return "processed";
}
const req = { id: 1 };
console.log(processOnce(req), processOnce(req));

try {
  new WeakMap().set("text", 1);
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node weak.js

🖥️ Output

2 [ 'name' ]
processed skipped
TypeError: Invalid value used as weak map key

Typical uses: caching results per object (memoisation), storing private data for objects, and tracking visited objects in recursive algorithms (the circular-JSON replacer in the JSON lesson uses a WeakSet).


🧪 Tester Scenario: Check Navigation Links and Count Errors

Two common checks: comparing the links on a page with the expected list, and counting error types in a log. Sets make the first precise, and a Map makes the second safe:

📄 links.js

const expectedLinks = new Set(["/", "/tutorials/", "/practice/", "/blogs/", "/contact/"]);
const foundOnPage = ["/", "/tutorials/", "/blogs/", "/blogs/", "/jobs/"];   // as read from the page

const found = new Set(foundOnPage);
const missing = [...expectedLinks.difference(found)];
const unexpected = [...found.difference(expectedLinks)];
const duplicates = foundOnPage.filter((link, i) => foundOnPage.indexOf(link) !== i);

console.log({ missing, unexpected, duplicates });
console.log(missing.length === 0 && unexpected.length === 0 ? "PASS" : "FAIL");

const log = ["TimeoutError", "AssertionError", "TimeoutError", "NetworkError", "TimeoutError"];
const errorCounts = new Map();
for (const e of log) errorCounts.set(e, (errorCounts.get(e) ?? 0) + 1);
const topError = [...errorCounts].sort((a, b) => b[1] - a[1])[0];
console.log(errorCounts, "most common:", topError);

⌨️ Terminal

node links.js

🖥️ Output

{
  missing: [ '/practice/', '/contact/' ],
  unexpected: [ '/jobs/' ],
  duplicates: [ '/blogs/' ]
}
FAIL
Map(3) {
  'TimeoutError' => 3,
  'AssertionError' => 1,
  'NetworkError' => 1
} most common: [ 'TimeoutError', 3 ]

Reporting which links are missing and which are unexpected gives a far better failure message than “arrays are not equal”.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Create a Map of country codes to names (IN, US, JP), then print the name for US, the size, and whether FR exists.

Show answer

📄 practice1.js

const countries = new Map([["IN", "India"], ["US", "United States"], ["JP", "Japan"]]);
console.log(countries.get("US"), countries.size, countries.has("FR"));

🖥️ Output

United States 3 false

Q2. Count how many times each word appears in "to be or not to be" using a Map.

Show answer

📄 practice2.js

const counts = new Map();
for (const word of "to be or not to be".split(" ")) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts);

🖥️ Output

Map(4) { 'to' => 2, 'be' => 2, 'or' => 1, 'not' => 1 }

Q3. Remove duplicates from ["qa", "dev", "qa", "ops", "dev"] and print how many unique values there are.

Show answer

📄 practice3.js

const teams = ["qa", "dev", "qa", "ops", "dev"];
const unique = [...new Set(teams)];
console.log(unique, unique.length);

🖥️ Output

[ 'qa', 'dev', 'ops' ] 3

Q4. Find the common elements of [1, 2, 3, 4] and [3, 4, 5], and the elements only in the first array, using Set methods.

Show answer

📄 practice4.js

const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log([...a.intersection(b)], [...a.difference(b)]);

🖥️ Output

[ 3, 4 ] [ 1, 2 ]

Q5. Convert the Map new Map([["env", "qa"], ["retries", 2]]) to a JSON string.

Show answer

📄 practice5.js

const settings = new Map([["env", "qa"], ["retries", 2]]);
console.log(JSON.stringify(settings));                       // a Map becomes {}
console.log(JSON.stringify(Object.fromEntries(settings)));  // convert first

🖥️ Output

{}
{"env":"qa","retries":2}

Q6. Check that every required permission ["read", "write"] is included in a user’s permissions ["read", "write", "delete"].

Show answer

📄 practice6.js

const required = new Set(["read", "write"]);
const granted = new Set(["read", "write", "delete"]);
console.log(required.isSubsetOf(granted));

🖥️ Output

true

🧠 MCQ Quiz: Map, Set, WeakMap, WeakSet

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which key types can a Map have?
  2. How do you get the number of entries in a Map?
  3. What does new Set([1, 1, 2]).size return?
  4. What does map.get("missing") return?
  5. How many items are in new Set([{ id: 1 }, { id: 1 }])?
  6. What does a.difference(b) return for Sets?
  7. Why can’t you iterate a WeakMap?
  8. What happens with new WeakSet().add("text")?
  9. What does JSON.stringify(new Map([["a", 1]])) return?
  10. When is a Map a better choice than a plain object?

💼 Interview Questions and Answers

Q1. What is the difference between a Map and an object?

A Map accepts keys of any type, keeps insertion order, has a size property, is directly iterable and has no inherited keys that can collide with your data. Objects only use string and symbol keys, inherit properties from Object.prototype, and need Object.keys/entries to iterate, but they are native to JSON and ideal for fixed records. Use a Map for dynamic key–value collections and an object for structured records.

Q2. How do you remove duplicates from an array?

For primitives, [...new Set(arr)]. For objects, deduplicate by a key: [...new Map(arr.map((o) => [o.id, o])).values()] (keeps the last occurrence of each id), or a filter with a Set of seen ids to keep the first.

📄 dedupe-first.js

const rows = [{ id: 1, v: "a" }, { id: 2, v: "b" }, { id: 1, v: "c" }];
const seen = new Set();
const firstOnly = rows.filter((r) => !seen.has(r.id) && seen.add(r.id));
console.log(firstOnly);

⌨️ Terminal

node dedupe-first.js

🖥️ Output

[ { id: 1, v: 'a' }, { id: 2, v: 'b' } ]

Q3. What are WeakMap and WeakSet used for?

They associate data with objects without preventing those objects from being garbage-collected: per-object caches, private data for class instances, and “already visited” tracking in graph or tree traversal. Because entries can disappear, they cannot be iterated and have no size, and keys must be objects.

Q4. How would you compare the expected and actual list of items on a page?

Convert both lists to Sets and compute expected.difference(actual) (missing items) and actual.difference(expected) (unexpected items); report both in the failure message. If order or duplicates matter, also compare the arrays themselves or check for duplicates separately, because Sets ignore both.


Advertisement

❓ Frequently Asked Questions

🤔 Is a Map faster than an object?

For frequent additions and deletions and large dynamic collections, Maps are usually faster. For small fixed records the difference does not matter.

🤔 Can I use Set methods like union in Node.js?

Yes. union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom are part of ES2025 and work in Node.js 22 and later.

🤔 How do I convert a Set to an array?

Use spread [...set] or Array.from(set). Then all array methods such as map and sort are available.

🤔 Does a Set keep the order of items?

Yes. Sets and Maps iterate in insertion order.


🏁 Summary

  • A Map stores key–value pairs with keys of any type, in insertion order, with get/set/has/delete and size.
  • Use Maps for dynamic keys, counting and caches; use objects for fixed records and JSON.
  • A Set stores unique values; [...new Set(arr)] removes duplicate primitives.
  • ES2025 Set methods (union, intersection, difference…) make expected-vs-actual comparisons simple.
  • WeakMap and WeakSet hold object keys weakly, so entries vanish with their objects; they are not iterable.

Next, continue with Lesson 37: Iterators and Generators.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in