JS

JavaScript Fundamentals

25 lessons

Progress0%
1. Introduction to JavaScript
1What is JavaScript?2Setting Up Your Environment
2. Variables and Data Types
1Declaring Variables2Data Types3Type Conversion
3. Operators
Arithmetic OperatorsComparison OperatorsLogical Operators
4. Control Flow
Conditional StatementsLoops
5. Functions
Function Basics
6. Arrays & Iteration
Array MethodsSpread, Rest & Destructuring
7. Objects & JSON
Working with ObjectsJSON & Optional Chaining
8. OOP & Classes
Class BasicsInheritance & Private Fields
9. Modules & Modern JS
ES ModulesModern JavaScript Features
10. Async JavaScript
PromisesAsync/Await
11. Error Handling
Error Types & try/catchCustom Errors & Debugging
12. Iterators & Advanced
Iterators & GeneratorsMap, Set & WeakRefs
All Tutorials
JavaScriptIterators & Advanced
Lesson 25 of 25 min
Chapter 12 · Lesson 2

Map, Set & WeakRefs

Map, Set & WeakRefs

JavaScript has four collection types beyond plain arrays and objects: Map, Set, WeakMap, and WeakSet. Each fills a specific niche.

Map vs Object

A Map is a key-value store where any value (including objects and functions) can be a key. Plain objects only support string/Symbol keys.

FeatureObjectMap
Key typesString, SymbolAny value
Insertion orderMostly preserved (ES2015+)Always preserved
SizeManual (Object.keys)map.size
Iterationfor...in / Object.entriesfor...of / map.forEach
Prototype pollutionPossibleNo inherited keys

Use a Map when: keys are non-strings, you need reliable insertion-order iteration, or you frequently add/remove keys.

Map Methods

js
const m = new Map();
m.set("key", "value");
m.get("key");       // "value"
m.has("key");       // true
m.delete("key");    // true
m.size;             // 0

Set vs Array

A Set stores unique values. It is ideal for deduplication and fast membership testing.

FeatureArraySet
DuplicatesAllowedNot allowed (automatically deduplicated)
LookupO(n) indexOfO(1) has()
OrderIndex-basedInsertion order

Set Methods

js
const s = new Set([1, 2, 2, 3]); // {1, 2, 3}
s.add(4);
s.has(2);      // true
s.delete(2);
s.size;        // 3

WeakMap & WeakSet (brief recap)

Covered in Section 9 — the key point is that they hold weak references to object keys, allowing GC to reclaim those objects when no strong references remain. They are non-iterable.

FinalizationRegistry & WeakRef (ES2021)

WeakRef holds a weak reference to an object. You dereference it with .deref(), which returns the object or undefined if it has been garbage collected. This is an advanced memory-management tool for caches and object pooling.

Code Examples

Map — Any Key Typejavascript
const map = new Map();

// String keys
map.set("name", "Alice");

// Object as key
const keyObj = { id: 1 };
map.set(keyObj, "object value");

// Function as key
const fn = () => {};
map.set(fn, "function value");

// Number as key
map.set(42, "forty-two");

console.log("size:", map.size);
console.log(map.get("name"));
console.log(map.get(keyObj));
console.log(map.get(42));

// Iteration (insertion order guaranteed)
for (const [key, value] of map) {
  const keyStr = typeof key === "object" ? JSON.stringify(key) : String(key);
  console.log(`${keyStr} => ${value}`);
}

// Initialize from entries
const scores = new Map([["Alice", 95], ["Bob", 80], ["Carol", 88]]);
const topScorer = [...scores.entries()].reduce(
  (best, [name, score]) => score > best[1] ? [name, score] : best,
  ["", 0]
);
console.log("Top scorer:", topScorer[0], topScorer[1]);

Map accepts any value as a key, including objects and functions — plain objects cannot. Map.size gives the count directly, and iteration respects insertion order.

Set — Unique Values & Operationsjavascript
// Deduplication
const nums = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(nums)];
console.log("Unique:", unique);

// Fast membership test
const allowed = new Set(["admin", "editor", "viewer"]);
console.log("admin allowed?",  allowed.has("admin"));
console.log("guest allowed?",  allowed.has("guest"));

// Set operations (union, intersection, difference)
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

const union        = new Set([...setA, ...setB]);
const intersection = new Set([...setA].filter((x) => setB.has(x)));
const difference   = new Set([...setA].filter((x) => !setB.has(x)));

console.log("Union:       ", [...union]);
console.log("Intersection:", [...intersection]);
console.log("Difference:  ", [...difference]);

Set automatically deduplicates values. Set.has() is O(1), making it far faster than Array.includes() for membership testing on large collections. Set operations (union, intersection, difference) are easy to express with spread and filter.

Choosing Map vs Object, Set vs Arrayjavascript
// CASE 1: Frequency counter — Map excels here
function charFrequency(str) {
  const freq = new Map();
  for (const ch of str) {
    freq.set(ch, (freq.get(ch) ?? 0) + 1);
  }
  return freq;
}

const freq = charFrequency("mississippi");
// Sort by frequency descending
const sorted = [...freq.entries()].sort((a, b) => b[1] - a[1]);
sorted.forEach(([ch, count]) => console.log(`'${ch}': ${count}`));

// CASE 2: Unique visitors — Set beats indexOf
const visits = ["alice", "bob", "alice", "carol", "bob", "alice"];
const uniqueVisitors = new Set(visits);
console.log("Unique visitors:", uniqueVisitors.size);
console.log("Bob visited?", uniqueVisitors.has("bob"));

Map is ideal for frequency counters and any key-value store needing non-string keys or reliable ordering. Set is ideal for tracking unique membership. Both provide O(1) lookup unlike arrays.

Quick Quiz

1. What type of keys can a Map use that a plain object cannot?

2. What is the time complexity of Set.has()?

3. How do you get the number of entries in a Map?

4. What is the main difference between WeakMap and Map?

Was this lesson helpful?

PreviousFinish