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.

Share
Published by
codeflare

Recent Posts

The Golden Ratio (φ)

1. What Is the Golden Ratio? The Golden Ratio, represented by the Greek letter φ (phi), is…

3 days ago

CSS Combinators

In CSS, combinators define relationships between selectors. Instead of selecting elements individually, combinators allow you to target elements based…

5 days ago

Boolean Algebra

Below is a comprehensive, beginner-friendly, yet deeply detailed guide to Boolean Algebra, complete with definitions, laws,…

7 days ago

Why It’s Difficult to Debug Other People’s Code (And what Can be Done About it)

Debugging your own code is hard enough — debugging someone else’s code is a whole…

1 week ago

Complete Git Commands

Git is a free, open-source distributed version control system created by Linus Torvalds.It helps developers: Learn how to…

1 week ago

Bubble Sort Algorithm

Bubble Sort is one of the simplest sorting algorithms in computer science. Although it’s not…

2 weeks ago