When should you use sets in Javascript?

Sets in JavaScript are ideal when you need to store unique elements where order doesn't matter and you primarily need to check for membership of different objects.

Sets are also useful when you want to perform operations like union, intersection, and difference similar to mathematical sets.

Let's explore both the built-in ES6 Set and understand when to use it effectively.

When to Use Sets

Use Sets when you need:

  • Unique values only ? Automatically prevents duplicates
  • Fast membership testing ? O(1) lookup time with has()
  • Set operations ? Union, intersection, difference between collections
  • Simple deduplication ? Remove duplicates from arrays

Basic Set Operations

The ES6 Set provides these essential methods:

  • add() ? Adds a new element to the set
  • clear() ? Removes all elements from the set
  • delete() ? Deletes a certain element from the set
  • has() ? Checks if a value exists in the set or not
  • values() ? Returns all the values in the set

Example: Basic Set Usage

// Create a new Set
let mySet = new Set();

// Add elements
mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate - won't be added
mySet.add('hello');

console.log('Set size:', mySet.size);
console.log('Has 2?', mySet.has(2));
console.log('Has 3?', mySet.has(3));

// Display all values
console.log('Values:', [...mySet]);
Set size: 3
Has 2? true
Has 3? false
Values: [ 1, 2, 'hello' ]

Example: Remove Duplicates from Array

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];

console.log('Original:', numbers);
console.log('Unique:', uniqueNumbers);
Original: [ 1, 2, 2, 3, 4, 4, 5 ]
Unique: [ 1, 2, 3, 4, 5 ]

Example: Set Operations

let setA = new Set([1, 2, 3, 4]);
let setB = new Set([3, 4, 5, 6]);

// Union
let union = new Set([...setA, ...setB]);
console.log('Union:', [...union]);

// Intersection
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log('Intersection:', [...intersection]);

// Difference
let difference = new Set([...setA].filter(x => !setB.has(x)));
console.log('Difference:', [...difference]);
Union: [ 1, 2, 3, 4, 5, 6 ]
Intersection: [ 3, 4 ]
Difference: [ 1, 2 ]

Sets vs Arrays Comparison

Feature Set Array
Unique elements Automatic Manual checking needed
Membership test O(1) with has() O(n) with includes()
Order preserved Insertion order Index-based order
Indexed access No Yes

Conclusion

Use Sets when you need unique values and fast membership testing. They're perfect for deduplication and mathematical set operations, making your code more efficient and readable.

Updated on: 2026-03-15T23:18:59+05:30

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements