JavaScript Set Reference Guide

🔑 JavaScript Set Reference – Quick Guide 1. Creation js const mySet = new Set(); // empty const letters = new Set(["a","b","c"]); // from array 2. Core Methods MethodPurposeExampleReturnsadd(value)Add elementmySet.add("x")Updated Setdelete(value)Remove elementmySet.delete("a")Booleanclear()Remove all elementsmySet.clear()Empty Sethas(value)Check existencemySet.has("b")true/falsesizeCount elementsmySet.sizeNumber 3. Iteration Methods MethodPurposeExampleforEach(callback)Run function for each valuemySet.forEach(v => console.log(v))values()Iterator of valuesfor (const v of mySet.values()) {}keys()Same as values()mySet.keys()entries()Iterator of [value, value] pairsmySet.entries() 4. Set Logic Methods (ES2025+) MethodPurposeunion(otherSet)Combine elements of both setsintersection(otherSet)Common elementsdifference(otherSet)Elements in one set but not the othersymmetricDifference(otherSet)Elements in either set but not bothisSubsetOf(otherSet)True if all elements are in other setisSupersetOf(otherSet)True if contains all elements of other setisDisjointFrom(otherSet)True if no common elements 5. Example Usage js const a = new Set([1,2,3]); const b = new Set([3,4,5]); console.log(a.union(b)); // {1,2,3,4,5} console.log(a.intersection(b)); // {3} console.log(a.difference(b)); // {1,2} console.log(a.symmetricDifference(b));// {1,2,4,5} 6. Key Notes Unique values only → duplicates ignored. Insertion order preserved. Sets are iterable (unlike WeakSets). Useful for mathematical set operations and fast membership checks. 🎯 Memory Hook Think of a Set as a mathematical set in code: No duplicates. Easy union/intersection/difference. Fast membership checks with .has().

To view or add a comment, sign in

Explore content categories