ποΈ Map, WeakMap, Set & WeakSet in JavaScript β Complete Guide
ποΈ Map, WeakMap, Set & WeakSet in JavaScript

Modern JavaScript provides powerful data structures for managing collections and key-value pairs.
Understanding Map, WeakMap, Set, and WeakSet is crucial for efficient code, memory management, and solving algorithmic problems.
In this blog, weβll cover:
πΉ Set
πΉ Map
πΉ WeakMap
πΉ WeakSet
πΉ Practice Questions Using These Structures
πΉ Set in JavaScript
A Set is a collection of unique values.
It automatically removes duplicates and allows fast lookup.
Example:
// Creating a Set
const mySet = new Set();
// Adding values
mySet.add(1);
mySet.add("hello");
mySet.add(true);
// Checking if a value exists
console.log(mySet.has(1)); // true
// Removing a value
mySet.delete("hello");
// Iterating through a Set
for (const value of mySet) {
console.log(value);
}
// Size of the Set
console.log(mySet.size); // 2
// Clearing all values
mySet.clear();
β Key Points
Stores unique values
Iterable with
for...ofProvides fast
add,delete,hasoperationsNo duplicate values
πΉ Map in JavaScript
A Map is a collection of key-value pairs.
Unlike objects, keys can be of any type (including objects).
Example:
// Creating a Map
const myMap = new Map();
// Adding key-value pairs
myMap.set("name", "Vishal");
myMap.set("age", 21);
// Getting a value
console.log(myMap.get("name")); // Vishal
// Checking if a key exists
console.log(myMap.has("age")); // true
// Removing a key-value pair
myMap.delete("age");
// Iterating through Map
for (const [key, value] of myMap) {
console.log(key, value);
}
// Size of the Map
console.log(myMap.size); // 1
// Clearing all entries
myMap.clear();
β Key Points
Keys can be any type
Maintains insertion order
Supports easy iteration
πΉ WeakMap in JavaScript
A WeakMap is similar to Map but keys must be objects and are weakly referenced.
This means if there are no other references to the object, it can be garbage collected.
Example:
let obj = { key: 'value' };
// Creating a WeakMap
let weakMap = new WeakMap();
weakMap.set(obj, 'metadata');
// Checking existence
console.log(weakMap.has(obj)); // true
// Removing strong reference
obj = null;
// The object can now be garbage collected
console.log(weakMap.has(obj)); // false
β Key Points
Keys must be objects
Weak reference allows automatic garbage collection
Not iterable (no
.keys()or.values())
πΉ WeakSet in JavaScript
A WeakSet is similar to Set, but only stores objects weakly.
They are useful for memory-sensitive applications.
Example:
let obj1 = { name: 'Vishal' };
let obj2 = { name: 'Sagar' };
const weakSet = new WeakSet();
weakSet.add(obj1);
weakSet.add(obj2);
console.log(weakSet.has(obj1)); // true
obj1 = null; // obj1 can be garbage collected automatically
β Key Points
Stores objects only
Weakly referenced β memory-efficient
Not iterable
π» Practice Questions Using Map & Set
Contains Duplicate β Use
Setto check duplicatesIntersection of Two Arrays β Use
Setfor efficient lookupDistribute Candies β Use
Setto count unique candiesLongest Consecutive Sequence β Use
Setfor O(n) solutionHappy Number β Track seen numbers using
SetFirst Unique Character In A String β Use
Mapfor countsFind Common Characters β Use
Mapfor character frequencySort Characters By Frequency β Use
MapandSetValid Sudoku β Use
Setfor row/column/subgrid validationLongest Substring Without Repeating Characters β Use
Setfor sliding window
π Practice Question Solutions β Map & Set in JavaScript
1οΈβ£ Contains Duplicate
Check if an array contains duplicate values.
const containsDuplicate = (nums) => {
const set = new Set(nums);
return set.size !== nums.length;
}
console.log(containsDuplicate([1,2,3,1])); // true
console.log(containsDuplicate([1,2,3])); // false
β
Time Complexity: O(n)
β
Space Complexity: O(n)
2οΈβ£ Intersection of Two Arrays
Return the intersection of two arrays (unique values).
const intersection = (nums1, nums2) => {
const set1 = new Set(nums1);
const result = new Set();
for (const num of nums2) {
if (set1.has(num)) result.add(num);
}
return [...result];
}
console.log(intersection([1,2,2,1], [2,2])); // [2]
β
Time Complexity: O(n + m)
β
Space Complexity: O(n)
3οΈβ£ Distribute Candies
Return the max number of unique candies.
const distributeCandies = (candies) => {
const unique = new Set(candies);
return Math.min(unique.size, candies.length / 2);
}
console.log(distributeCandies([1,1,2,2,3,3])); // 3
β
Time Complexity: O(n)
β
Space Complexity: O(n)
4οΈβ£ Longest Consecutive Sequence
Find the length of the longest consecutive elements sequence.
const longestConsecutive = (nums) => {
const set = new Set(nums);
let longest = 0;
for (const num of set) {
if (!set.has(num - 1)) {
let current = num;
let streak = 1;
while (set.has(current + 1)) {
current++;
streak++;
}
longest = Math.max(longest, streak);
}
}
return longest;
}
console.log(longestConsecutive([100,4,200,1,3,2])); // 4
β
Time Complexity: O(n)
β
Space Complexity: O(n)
5οΈβ£ Happy Number
Determine if a number eventually reaches 1 by repeatedly summing the squares of its digits.
const isHappy = (n) => {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = n.toString()
.split('')
.reduce((sum, d) => sum + Math.pow(Number(d), 2), 0);
}
return n === 1;
}
console.log(isHappy(19)); // true
console.log(isHappy(2)); // false
β
Time Complexity: O(log n) per iteration
β
Space Complexity: O(log n)
6οΈβ£ First Unique Character In A String
const firstUniqChar = (s) => {
const map = new Map();
for (const char of s) {
map.set(char, (map.get(char) || 0) + 1);
}
for (let i = 0; i < s.length; i++) {
if (map.get(s[i]) === 1) return i;
}
return -1;
}
console.log(firstUniqChar("leetcode")); // 0
console.log(firstUniqChar("loveleetcode")); // 2
β
Time Complexity: O(n)
β
Space Complexity: O(n)
7οΈβ£ Find Common Characters
const commonChars = (words) => {
const result = [];
let map = new Map();
for (const char of words[0]) {
map.set(char, (map.get(char) || 0) + 1);
}
for (let i = 1; i < words.length; i++) {
const temp = new Map();
for (const char of words[i]) {
if (map.has(char) && map.get(char) > 0) {
temp.set(char, (temp.get(char) || 0) + 1);
map.set(char, map.get(char) - 1);
}
}
map = temp;
}
for (const [char, count] of map) {
for (let i = 0; i < count; i++) result.push(char);
}
return result;
}
console.log(commonChars(["bella","label","roller"])); // ["e","l","l"]
β
Time Complexity: O(n * m) (n = number of words, m = max word length)
β
Space Complexity: O(26)
8οΈβ£ Sort Characters By Frequency
const frequencySort = (s) => {
const map = new Map();
for (const char of s) {
map.set(char, (map.get(char) || 0) + 1);
}
return [...s].sort((a, b) => map.get(b) - map.get(a)).join('');
}
console.log(frequencySort("tree")); // "eert" or "eetr"
β
Time Complexity: O(n log n)
β
Space Complexity: O(n)
9οΈβ£ Valid Sudoku
const isValidSudoku = (board) => {
const rows = [], cols = [], boxes = [];
for (let i = 0; i < 9; i++) {
rows.push(new Set());
cols.push(new Set());
boxes.push(new Set());
}
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const val = board[r][c];
if (val === ".") continue;
const boxIndex = Math.floor(r / 3) * 3 + Math.floor(c / 3);
if (rows[r].has(val) || cols[c].has(val) || boxes[boxIndex].has(val)) return false;
rows[r].add(val);
cols[c].add(val);
boxes[boxIndex].add(val);
}
}
return true;
}
β
Time Complexity: O(1) (board size fixed 9x9)
β
Space Complexity: O(1)
π Longest Substring Without Repeating Characters
const lengthOfLongestSubstring = (s) => {
const set = new Set();
let left = 0, maxLen = 0;
for (let right = 0; right < s.length; right++) {
while (set.has(s[right])) {
set.delete(s[left]);
left++;
}
set.add(s[right]);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
console.log(lengthOfLongestSubstring("abcabcbb")); // 3
β
Time Complexity: O(n)
β
Space Complexity: O(min(n, charset size))
π― Final Thoughts
Use Set for unique values
Use Map for key-value pairs with any key type
Use WeakMap/WeakSet for memory-sensitive objects
Perfect for algorithmic challenges and real-world applications
π― Summary
Set / WeakSet β Unique elements, memory efficient
Map / WeakMap β Key-value pairs, any key type (Weak β garbage collected)
These structures are great for solving common algorithm problems efficiently



