JavaScript Set

Why should you care about JavaScript Set?

Set is one of the easiest ways to clean duplicate data. If you work with tags, IDs, filters, or user inputs, Set helps you keep values unique with less code.

A Set works like a guest list where each name can appear only once. It stores unique values, so if you add a duplicate, JavaScript ignores it automatically.

You can store almost any type of value in a Set: numbers, strings, objects, and more. Whenever you need a collection without duplicates, Set is usually the cleanest option.

A Set treats primitive values such as 1, "1", and true as different values. It also keeps only one NaN, but objects are compared by reference, so two separately created objects are still different values even when they contain the same properties.

A Set keeps unique values
Repeated values do not create a second entry.
Input: [1, 2, 3, 2, 1]
Build: new Set()
Stored: 1, 2, 3
const values = [1, 2, 3, 2, 1];
const unique = new Set(values);
[...unique]; // [1, 2, 3]
Iteration follows the order of first insertion.

javascript

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

console.log(mySet); // Set(3) { 1, 2, 3 }
// Duplicates are automatically removed

Create a Set and watch duplicate values be ignored.

Create a Set with new Set(). You can start from an array, or create an empty Set and add values as your program runs.

The constructor accepts an iterable, such as an array, string, or another Set. Each item from that iterable is added in order, and duplicates are removed as the new Set is created.

Create a set of unique values
[...new Set([1, 1, 2])]
Returns: [1, 2]

javascript

// Empty Set
const emptySet = new Set();
emptySet.add(10);
emptySet.add(20);
console.log(emptySet); // Set(2) { 10, 20 }

// Set from an array
const numSet = new Set([1, 2, 3]);
console.log(numSet); // Set(3) { 1, 2, 3 }

// Duplicate values are ignored
const colors = new Set(["red", "blue", "red", "green"]);
console.log(colors); // Set(3) { 'red', 'blue', 'green' }

Sets keep values in the order you add them. When you iterate, values come out in that same sequence. This behavior is called insertion order.

Set iteration follows insertion order. When you iterate over a Set, values are returned in the order they were added.

Keep insertion order
[...new Set([3, 1, 3, 2])]
Returns: [3, 1, 2]

javascript

const mySet = new Set();
mySet.add("read");
mySet.add("write");
mySet.add("delete");

// Values come out in insertion order
for (const perm of mySet) {
  console.log(perm);
}
// read
// write
// delete

Sets come with a handful of handy methods (plus one property). Here's a quick overview:

  • size - returns the number of elements (property, not a method).
  • add(value) - adds a new value to the Set.
  • has(value) - returns true if the value exists.
  • delete(value) - removes a specific value.
  • clear() - removes all values from the Set.
  • forEach(callback) - iterates over each value.
  • values() - returns an iterator of all values.

Let's go through each one with examples.

Common Set operations
Use methods for membership and size for the count.
add(value): Inserts a value and returns the Set.
has(value): Returns true if the value is present.
delete(value): Returns true if it removed the value.
clear(): Removes every value.
size: Counts the values currently in the Set.
const values = new Set([1, 2]);
values.add(3);
values.has(2); // true
values.size; // 3

size tells you how many values are in your Set. It's a property, not a method, so you write mySet.size without parentheses.

This is similar to array.length in arrays. The count updates automatically when you add or remove values.

Count unique values
new Set([1, 1, 2]).size
Returns: 2

javascript

const mySet = new Set([10, 20, 30, 20]);

console.log(mySet.size); // 3 (not 4, because 20 is a duplicate)

mySet.add(40);
console.log(mySet.size); // 4

mySet.delete(10);
console.log(mySet.size); // 3

Want to know if a value is in your Set? That's what has() is for. It returns true if the value exists and false if it doesn't.

Set is generally a better choice for repeated membership checks because has() is designed for checking whether a value exists in the Set. Actual performance depends on the data and JavaScript engine.

Check membership
new Set([1, 2]).has(2)
Returns: true

javascript

const permissions = new Set(["read", "write", "delete"]);

console.log(permissions.has("write")); // true
console.log(permissions.has("admin")); // false

Check membership, delete a value, and read size.

Use delete() to remove a value from your Set. It returns true if the value was found and removed, or false if it wasn't there.

Delete one value
const set = new Set([1, 2]);
set.delete(2)
Returns: true
Afterward: [...set]: [1]

javascript

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

console.log(nums.delete(3)); // true  - 3 was removed
console.log(nums.delete(9)); // false - 9 was not in the Set

console.log(nums); // Set(3) { 1, 2, 4 }

Two more commonly used Set methods are add() and clear().

add(value) puts a new value into your Set. If the value already exists, nothing happens (no error). clear() wipes everything out and leaves the Set empty.

Add and clear values
const set = new Set();
set.add(1);
set.clear()
Result: undefined
Afterward: set.size: 0

javascript

const mySet = new Set();

// add()
mySet.add("a");
mySet.add("b");
mySet.add("a"); // duplicate, ignored
console.log(mySet); // Set(2) { 'a', 'b' }

// clear()
mySet.clear();
console.log(mySet);      // Set(0) {}
console.log(mySet.size); // 0

The add() method returns the Set itself, so you can chain multiple add() calls together: mySet.add(1).add(2).add(3).

Sets do not support indexes. Unlike arrays, you cannot access a Set element by its position using bracket notation like mySet[0].

That's on purpose. Sets are built for answering "is this value in here?" not "what's at position 3?" If you need index access, convert the Set to an array first.

Use membership, not an index
const set = new Set(["a", "b"]);
set[0]
Result: undefined

javascript

const mySet = new Set([10, 20, 30]);

// This does NOT work - Sets have no index
console.log(mySet[0]); // undefined

// Convert to array first if you need index access
const arr = [...mySet];
console.log(arr[0]); // 10
console.log(arr[1]); // 20

See why Set membership uses has() instead of numeric indexes.

The easiest way to loop through a Set is with a for...of loop. You'll get each value in the order it was added.

Loop over a Set
for...of reads each value in insertion order.
First: JavaScript
Second: Python
Third: Java
const languages = new Set([
  "JavaScript", "Python", "Java",
]);
for (const language of languages) {
  console.log(language);
}
languages.values() gives the same order.

javascript

const languages = new Set(["JavaScript", "Python", "Java"]);

for (const lang of languages) {
  console.log(lang);
}
// JavaScript
// Python
// Java

You can also use set.values() to get an iterator and loop over that instead. Either way, you get the same result.

javascript

const nums = new Set([5, 10, 15]);

for (const val of nums.values()) {
  console.log(val);
}
// 5
// 10
// 15

Iterate through unique Set values in insertion order.

You can turn a Set into a regular array in two ways: the spread operator ([...set]) or Array.from(). Both do the same thing.

Why convert? Because Sets don't have map(), filter(), or reduce(). Turn it into an array and you get all those methods back.

Copy set values to an array
const set = new Set([1, 2]);
[...set]
Returns: [1, 2]

javascript

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

// Using spread operator
const arr1 = [...mySet];
console.log(arr1); // [1, 2, 3, 4]

// Using Array.from()
const arr2 = Array.from(mySet);
console.log(arr2); // [1, 2, 3, 4]

// Practical use - remove duplicates from an array
const withDups = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(withDups)];
console.log(unique); // [1, 2, 3, 4]

Remove duplicates with a Set and convert back to an array.

forEach() lets you run a function on every value in the Set, one at a time, in the order they were added.

Set's forEach() passes the same value as both its first and second callback arguments. The third argument is the Set itself.

Visit values with forEach()
The callback runs once per value in insertion order.
First two arguments: Both contain the current value, not an index.
Third argument: The Set being visited.
const colors = new Set(["red", "green", "blue"]);
colors.forEach(color => {
  console.log(color.toUpperCase());
});
Prints RED, GREEN, then BLUE.

javascript

const colors = new Set(["red", "green", "blue"]);

 colors.forEach(function(value, valueAgain, set) {
  console.log(value);
});
// red
// green
// blue

// Using arrow function
colors.forEach(color => console.log(color.toUpperCase()));
// RED
// GREEN
// BLUE

A WeakSet stores objects and non-registered Symbol values as weak references. It cannot store ordinary primitive values such as strings or numbers.

WeakSet entries are weakly held, so an object or non-registered Symbol is not kept alive solely by its presence in a WeakSet. A WeakSet is not iterable and has no size property.

Track object membership
const item = {};
const seen = new WeakSet([item]);
seen.has(item)
Returns: true

javascript

const ws = new WeakSet();

let obj1 = { role: "editor" };
let obj2 = { role: "viewer" };

ws.add(obj1);
ws.add(obj2);

console.log(ws.has(obj1)); // true

obj1 = null; // If no other references remain, obj1 may eventually be garbage-collected

// WeakSet only supports: add(), has(), delete()
// ws.size and for...of are NOT available

WeakSets are handy when you want to "tag" objects (like DOM elements) without keeping them alive in memory after they're no longer used.

A common Set workflow is: accept an array, remove duplicates, then convert back to an array for sorting or map(). Set membership is usually a better fit than repeatedly scanning a large array, but a Set uses memory and does not replace an array when order-by-index matters.

Deduplicate, check, and convert
Keep the Set for repeated membership checks.
Deduplicate: Build a Set from the original values once.
Check membership: Use has() instead of scanning the array.
Convert: Spread the Set when you need array methods.
const tags = ["js", "web", "js", "css", "web"];
const unique = new Set(tags);
unique.has("css"); // true
[...unique]; // ["js", "web", "css"]

This is the practical Array → Set → Array workflow: use a Set to remove duplicates, then convert it back when you need array methods or index-based output.

javascript

const tagsFromUsers = ["js", "web", "js", "css", "web"];

// Deduplicate while preserving first-seen insertion order.
const uniqueTags = [...new Set(tagsFromUsers)];
console.log(uniqueTags); // ["js", "web", "css"]

// Convert back when array methods are needed.
const uppercaseTags = uniqueTags.map(tag => tag.toUpperCase());
console.log(uppercaseTags); // ["JS", "WEB", "CSS"]
Choose an array or Set based on the operation you need.
NeedPreferReason
Index access, sorting, or ordered transformationsArrayArrays provide indexes and methods such as map, filter, and reduce.
Remove duplicates oncenew Set(array)Short and preserves insertion order.
Repeated membership checksSethas() is designed for membership lookup instead of scanning from the beginning each time.
Store duplicate recordsArraySet intentionally removes repeated values.

Big-O descriptions are useful for intuition, not guarantees for every JavaScript engine. Benchmark realistic data if performance matters. Object values are compared by reference, so two separate objects with identical properties are still two Set entries.

Practical rule: use Set for uniqueness and membership; convert to an array when you need array-specific operations or index-based output.

Let's wrap up everything we covered:

  • A Set stores unique values - no duplicates allowed.
  • Sets maintain insertion order.
  • size is a property that returns the count of elements.
  • add(), has(), delete(), and clear() are the core methods.
  • Use for...of or forEach() to iterate over values.
  • Convert a Set to an array with [...set] or Array.from(set).
  • Sets do not support index-based access.
  • A WeakSet weakly holds objects and non-registered Symbols; it is not iterable and has no size property.

What's next? Now that you understand Sets, let's move on to key-value collections with the next tutorial.

Videos for this topic will be added soon.

Reviewed by

SimplyJavaScript Editorial Team

Technical editors and JavaScript educators with hands-on experience building frontend projects, writing learning material, and reviewing tutorials for clarity, accuracy, and beginner-friendly guidance.