JavaScript Set vs Array: Unique Values and Fast Membership Checks

Day 39/50 – JavaScript Interview Question? Question: What is the Set object and how does it differ from an Array? Simple Answer: A Set is a collection of unique values where duplicates are automatically removed. Unlike arrays, Sets don't have indices, maintain insertion order but optimized for checking membership (has()), and provide methods like add(), delete(), and clear(). 🧠 Why it matters in real projects: Sets are perfect for removing duplicates, checking membership (much faster than array.includes() for large datasets), implementing tags/categories, and maintaining unique collections. Operations like has(), add(), and delete() are O(1) compared to array's O(n). 💡 One common mistake: Trying to access Set elements by index (not possible) or expecting Sets to store objects by value rather than reference. Two objects with identical properties are considered different in a Set. 📌 Bonus: // Creating Sets const set = new Set([1, 2, 3, 2, 1]); // Set { 1, 2, 3 } const set2 = new Set('hello'); // Set { 'h', 'e', 'l', 'o' } // Basic operations set.add(4); // Add element set.has(2); // true - O(1) operation! set.delete(3); // Remove element set.size; // 3 (not length) set.clear(); // Remove all // Removing duplicates from array const nums = [1, 2, 2, 3, 3, 4]; const unique = [...new Set(nums)]; // [1, 2, 3, 4] // Performance comparison const arr = Array(1000000).fill(0).map((_, i) => i); const set3 = new Set(arr); // Array: O(n) - slow for large datasets console.time('array'); arr.includes(999999); console.timeEnd('array'); // ~5ms // Set: O(1) - constant time console.time('set'); set3.has(999999); console.timeEnd('set'); // ~0.01ms // Set operations (custom implementations) // Union const setA = new Set([1, 2, 3]); const setB = new Set([3, 4, 5]); const union = new Set([...setA, ...setB]); // Set { 1, 2, 3, 4, 5 } // Intersection const intersection = new Set( [...setA].filter(x => setB.has(x)) ); // Set { 3 } // Difference const difference = new Set( [...setA].filter(x => !setB.has(x)) ); // Set { 1, 2 } // Object reference gotcha const obj1 = { id: 1 }; const obj2 = { id: 1 }; const objSet = new Set([obj1, obj2]); console.log(objSet.size); // 2 (different references!) // Iteration for (let value of set) { console.log(value); // Sets are iterable } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories