Course contentsShow
← JavaScript
Lesson 1045 of 2,72324. Maps and SetsFree lesson

Creating Sets

Create Sets using the constructor, from arrays, and from other iterables.

Creating Sets

You'll learn how to create new Set objects in JavaScript using different approaches.

What is Set Creation?

Now that you know what a Set is (a collection of unique values), it's time to learn the different ways you can actually create one. JavaScript gives you several flexible options depending on your data source.

The Three Main Ways

Using the Constructor with No Arguments

The simplest way creates an empty Set:

const emptySet = new Set();
console.log(emptySet.size); // 0

Creating from an Array

Pass an array directly to the constructor. Duplicates are automatically removed:

const numbers = new Set([1, 2, 3, 2, 1]);
console.log(numbers.size); // 3 (duplicates removed)
console.log(numbers); // Set { 1, 2, 3 }

const names = new Set(['Alice', 'Bob', 'Alice']);
console.log(names.size); // 2

Creating from Other Iterables

Any iterable works—strings, Maps, other Sets, or custom iterables:

// From a string (each character becomes an element)
const letters = new Set('hello');
console.log(letters); // Set { 'h', 'e', 'l', 'o' }
console.log(letters.size); // 4 (one 'l' removed)

// From another Set
const original = new Set([1, 2, 3]);
const copy = new Set(original);
console.log(copy); // Set { 1, 2, 3 }

Why This Matters

Creating Sets from arrays is a powerful pattern for quickly removing duplicates from data. Since the constructor accepts any iterable, you have flexibility in your data sources.

Key Takeaway: Create Sets using new Set() for empty Sets, new Set(array) to convert arrays (removing duplicates), or new Set(iterable) from any iterable like strings or other Sets.