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

API Design Principles

How to Build APIs That Are Easy to Use, Scale, and Maintain Learn on the…

1 week ago

JavaScript vs Your Expectations

Almost everyone starts learning JavaScript with the wrong expectations. Let's fix them. Download the Codeflare…

2 weeks ago

Introduction to Phaser JS

Phaser JS is a powerful, open-source HTML5 game development framework used for creating 2D games that…

3 weeks ago

Web Authentication Libraries

JavaScript / Node.js Authentication Libraries 1. Passport.js One of the most popular authentication middleware libraries…

3 weeks ago

The Things They Carry: Software Developers Starter Packs

Every profession comes with its own set of tools. A carpenter has a toolbox, a…

3 weeks ago

CRUD Operations: The Foundation of Data Management

Every application that stores and manages data relies on a set of basic operations known…

1 month ago