JavaScript•Sets
JavaScript Set: Unique Collections and Deduplication
Set eliminates duplicates automatically and provides fast O(1) membership checks with .has().
Syntax
const mySet = new Set([1, 2, 2, 3]);
mySet.add(4);
mySet.has(2);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| add(val) | Method | Appends a new unique element to the set. |
| has(val) | Method | Returns boolean indicating whether element exists. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// Deduplicating Arrays with Set
const rawTags = ["javascript", "react", "node", "react", "typescript", "node"];
const uniqueTags = [...new Set(rawTags)];
console.log("Raw Tags (length " + rawTags.length + "):", rawTags);
console.log("Unique Tags (length " + uniqueTags.length + "):", uniqueTags);
// Fast membership testing
const allowedRoles = new Set(["ADMIN", "SUPERUSER"]);
console.log("Is MODERATOR allowed?", allowedRoles.has("MODERATOR"));
console.log("Is ADMIN allowed?", allowedRoles.has("ADMIN"));Expected Output:
Raw Tags (length 6): [ 'javascript', 'react', 'node', 'react', 'typescript', 'node' ] Unique Tags (length 4): [ 'javascript', 'react', 'node', 'typescript' ] Is MODERATOR allowed? false Is ADMIN allowed? true
How It Works: Step-by-Step
- Lines 2-3: Converts array with duplicates to Set and spreads back to unique array.
- Lines 9-11: Demonstrates O(1) set membership check with has().
Key Concepts
- new Set(array) instantly deduplicates primitive values.
- Set uses SameValueZero equality (similar to ===, but considers NaN equal to NaN).
- Set size is retrieved with the .size property.
Common Mistake: Expecting Set to deduplicate object references with identical properties
Two distinct object literals have different memory references and are not considered equal by Set.
❌ Incorrect
const s = new Set([{ id: 1 }, { id: 1 }]); // Set has size 2!✅ Correct
const s = new Set();
const obj = { id: 1 };
s.add(obj);
s.add(obj); // Correct: only 1 entryRelated JavaScript Tutorials & Compiler
JavaScript Arrays: Methods (map, filter, reduce, slice)
Master modern array manipulation using push, pop, slice, map, filter, and reduce.
JavaScript Objects and Map: Key-Value Data Structures
Learn differences between plain JavaScript Objects and the ES6 Map collection.
JavaScript Strings: Template Literals, Regex, and Methods
Explore string methods (split, replace, trim, includes) and template strings.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.