Set and WeakSet are both collections for storing unique values, but they have important differences:
// Set — stores any values
const set = new Set([1, 2, 'hello', {}]);
// WeakSet — only objects
const obj = {};
const weakSet = new WeakSet([obj]);Think of Set as a regular box where you can put anything: toys, books, clothes. And WeakSet is a magical box that throws away things when no one needs them anymore! 📦✨
// Set can store anything
const set = new Set();
set.add(1); // number ✅
set.add('text'); // string ✅
set.add({}); // object ✅
// WeakSet only objects
const weakSet = new WeakSet();
// weakSet.add(1); // ❌ Error!
// weakSet.add('text'); // ❌ Error!
weakSet.add({}); // ✅ Only objectsconst set = new Set([1, 2, 3]);
// Set can be iterated
for (const item of set) {
console.log(item); // 1, 2, 3
}
const weakSet = new WeakSet([{a: 1}, {b: 2}]);
// ❌ WeakSet cannot be iterated!
// for (const item of weakSet) // Error!WeakSet is like a friend who only remembers people you’re still in touch with. If a person has left your life (no one holds a reference to them anymore), WeakSet forgets them automatically! 🧠
let obj = { name: 'John' };
const weakSet = new WeakSet([obj]);
// When obj is no longer used by anyone
obj = null;
// Object will be automatically removed from WeakSet
// Garbage collector takes care of it 🗑️// Unique users
const uniqueUsers = new Set();
// Unique tags
const tags = new Set(['js', 'css', 'html', 'js']);
// Will only have ['js', 'css', 'html']// Need to go through all elements
const numbers = new Set([1, 2, 3]);
numbers.forEach(num => {
console.log(num); // 1, 2, 3
});// Track already processed objects
const processed = new WeakSet();
function process(obj) {
if (processed.has(obj)) {
return 'already processed';
}
processed.add(obj);
return 'processed';
}// Check if we've already processed this node
const visited = new WeakSet();
function traverse(node) {
if (visited.has(node)) {
return; // Already been here
}
visited.add(node);
// Process node...
}// ❌ Error!
const weakSet = new WeakSet();
// weakSet.add('string'); // TypeError!
// weakSet.add(123); // TypeError!
// ✅ Correct
const obj = {};
weakSet.add(obj); // Only objects!// ❌ Cannot iterate WeakSet
const weakSet = new WeakSet([{a: 1}]);
// weakSet.forEach(item => {}); // Error!Understanding the difference between Set and WeakSet helps choose the right tool for the job and avoid memory issues! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪