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.

JavaScript Set - unique values, Set methods (add, has, delete, size, clear), Set vs Array comparison, and iteration

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

Creating a JavaScript Set from an iterable

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.

JavaScript Set insertion order

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.

JavaScript Set functions overview

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.

JavaScript Set size property

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.

JavaScript Set has method

javascript

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

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

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.

JavaScript Set delete method

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.

JavaScript Set add and clear methods

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.

JavaScript Sets do not support indexes

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

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.

Looping over a JavaScript Set with for of

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

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.

Converting a JavaScript Set to an array

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]

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.

JavaScript Set forEach method

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 is like a Set with two restrictions: it can only store objects (no strings or numbers), and it holds weak references to them.

WeakSet holds weak references to objects. If an object is no longer reachable elsewhere, it can eventually be garbage-collected without the WeakSet keeping it alive. WeakSet is not iterable and has no size property.

JavaScript WeakSet stores objects with weak references

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.

JavaScript Set deduplication and lookup workflow

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 holds weak references to objects and is not iterable.

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.