What is a Set?

A 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.

codeflare

Latest tech news and coding tips.

Share
Published by
codeflare

Recent Posts

Backpressure in Node.js

Backpressure is a flow-control mechanism that prevents a fast data producer from overwhelming a slower data…

5 days ago

JavaScript Collections

JavaScript collections are data structures used to store, organize, retrieve, and manipulate groups of values. Choosing…

5 days ago

Context Poisoning Explained

Context poisoning is a technique where an attacker deliberately places misleading, malicious, or irrelevant information into…

1 week ago

Common React Errors

React makes building user interfaces easier, but certain errors appear repeatedly, especially when working with…

3 weeks ago

C Programming Cheat Sheet

The C programming language is a foundational, general-purpose computer programming language created by Dennis Ritchie at Bell Labs in 1972. Originally developed to…

3 weeks ago

Homebrew Tutorial

What Is Homebrew? Homebrew is a package manager for macOS and Linux that makes it easy to…

3 weeks ago