What is a Set?

Set in JavaScript is a built-in object that lets you store unique values of any type.
Unlike arrays, a Set does not allow duplicate entries — each value appears only once.

Think of it like a real-world set of items: no duplicates, no ordering rules, just pure uniqueness.

const mySet = new Set([1, 2, 3, 3]);
console.log(mySet); 
// Output: Set(3) { 1, 2, 3 }

Even though 3 appears twice, the Set keeps only one instance.

Achieve your career goals, switch to tech and learn software development in Abuja

Why Use a Set?

Using a Set gives you useful advantages:

1. Uniqueness guaranteed

Perfect when you need distinct values (e.g., unique users, tags, IDs).

2. Faster lookup than arrays

Checking if a value exists is O(1) in a Set, while arrays take O(n).

3. Easy to remove duplicates from arrays

One line of code!

const uniqueArray = [...new Set([1,1,2,3,3])];
// [1, 2, 3]

4. Clean, mathematical set operations

Union, intersection, difference — very easy to implement.

How to Create a Set

1. Empty Set

const s = new Set();

2. Set with initial values

const s = new Set([1, 2, 3]);

Core Set Methods

1. .add(value)

Adds a value to the Set.

const s = new Set();
s.add(10);
s.add(20);
s.add(10); // ignored because 10 already exists

2. .delete(value)

Removes a value if it exists.

s.delete(20);

3. .has(value)

Checks if a value exists inside the Set.

console.log(s.has(10)); // true
console.log(s.has(99)); // false

4. .clear()

Removes all items.

s.clear();
console.log(s.size); // 0

5. .size

Property that shows the number of unique elements.

console.log(s.size);

Iterating Through a Set

Sets are iterable. You can loop through them in different ways:

1. for...of

const fruits = new Set(["apple", "banana", "orange"]);

for (let fruit of fruits) {
  console.log(fruit);
}

2. .forEach()

fruits.forEach(f => console.log(f));

3. Convert Set → Array

Useful for indexing or using array methods.

const arr = [...fruits];
console.log(arr);

Removing Duplicates from an Array (Most Common Use Case)

const students = ["Ada", "Ben", "Ben", "Lara"];

const uniqueStudents = [...new Set(students)];

console.log(uniqueStudents);
// ["Ada", "Ben", "Lara"]

Real-World Use Cases of Sets

1. Tracking unique visitors

const visitors = new Set();
visitors.add("user1");
visitors.add("user2");
visitors.add("user1"); // ignored

2. Ensuring unique tags in a blog post

const tags = ["js", "tech", "js", "web"];
const uniqueTags = [...new Set(tags)];

3. Removing duplicates from API data

4. Creating mathematical set operations

Mathematical Operations Using Sets

1. Union (A ∪ B)

Combine items from both sets.

const A = new Set([1,2]);
const B = new Set([2,3]);

const union = new Set([...A, ...B]);
// Set {1, 2, 3}

2. Intersection (A ∩ B)

Values that appear in both sets.

const intersection = new Set([...A].filter(x => B.has(x)));
// Set {2}

3. Difference (A − B)

Values in A that are not in B.

const difference = new Set([...A].filter(x => !B.has(x)));
// Set {1}

Important Things to Know About Sets

1. Sets do not support indexing

This will not work:

console.log(s[0]); // undefined

2. Sets preserve insertion order

Even though they don’t support indexing, they remember the order in which items were added.

3. NaN equals NaN in Sets

This is different from regular equality in JavaScript.

new Set([NaN, NaN]); // Set { NaN }

Set vs Array — When to Use What

FeatureSetArray
Allows duplicates❌ No✅ Yes
Indexed access❌ No✅ Yes
Fast existence check✅ Yes❌ No
Useful for uniqueness✅ Excellent❌ Requires work
Order preserved✔️ Yes✔️ Yes

Summary

  • A Set stores unique values.
  • Supports: add, delete, has, clear.
  • Great for removing duplicates quickly.
  • Perfect for fast membership tests.
  • Useful for mathematical operations like union, intersection, difference.

Recent Posts

Essential VS Code Extensions Every Developer Should Use

Visual Studio Code (VS Code) is powerful out of the box, but its real strength…

1 week ago

JavaScript Variables

1. What Is a Variable in JavaScript? A variable is a named container used to store data…

1 week ago

C++ Queue

1. What Is a Queue? A Queue is a linear data structure that follows the principle: FIFO – First…

1 week ago

Must-Know Angular Concepts

Angular is a full-featured frontend framework built by Google for creating large, maintainable, and high-performance web applications.…

2 weeks ago

Responsive Web Design (RWD)

What Is Responsive Web Design? Responsive Web Design (RWD) is an approach to building websites…

2 weeks ago

Geolocation API in JavaScript

The Geolocation API allows a web application to access a user’s geographical location (latitude, longitude, and more), with…

2 weeks ago