JavaScript Set Object: Complete Guide

Learn the JavaScript Set object for storing unique values of any type. Covers add, delete, has, iteration, removing duplicates, and set operations.

6 min read

A Set is a built-in JavaScript collection that stores unique values. Unlike an array, a Set automatically prevents duplicates. Add the same value twice and only one copy is kept. This makes Set perfect for tracking unique items, removing duplicates, and membership testing.

javascriptjavascript
const tags = new Set();
 
tags.add("javascript");
tags.add("web");
tags.add("javascript"); // Duplicate -- silently ignored
 
console.log(tags.size); // 2
console.log(tags.has("javascript")); // true

Basic Operations

add(), delete(), has(), clear(), and size are the core methods you will use for almost every Set. Adding a value and checking membership are the two most common operations:

javascriptjavascript
const colors = new Set();
 
colors.add("red");
colors.add("blue");
colors.add("green");
 
console.log(colors.size);        // 3
console.log(colors.has("blue")); // true

Removing a single value or clearing the whole Set works the same way it does on a Map, and size always reflects the current count:

javascriptjavascript
colors.delete("blue");
console.log(colors.has("blue")); // false
console.log(colors.size);        // 2
 
colors.clear();
console.log(colors.size);        // 0

The add() method returns the Set itself, which lets you chain several additions in a single expression instead of repeating the variable name:

javascriptjavascript
const letters = new Set();
letters.add("a").add("b").add("c");
 
console.log(letters.size); // 3

Creating a Set from an Array

Pass any iterable, such as an array, string, or another Set, to the constructor to populate a new Set with its values in one step:

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

This is the most common Set pattern: converting an array to a Set to strip duplicates, then spreading back to an array.

Removing Duplicates from an Array

The classic one-liner for deduplication:

javascriptjavascript
const items = ["apple", "banana", "apple", "orange", "banana"];
const unique = [...new Set(items)];
 
console.log(unique); // ["apple", "banana", "orange"]

This works for primitive values. For arrays of objects, duplicates are determined by reference identity, not property values. Two objects with the same properties are different references and will both be kept.

Iterating Over a Set

Set is iterable. You can use for...of, forEach(), values(), and keys():

javascriptjavascript
const fruits = new Set(["apple", "banana", "orange"]);
 
for (const fruit of fruits) {
  console.log(fruit);
}
 
fruits.forEach(value => {
  console.log(value);
});

Set's keys() and values() are identical; both return the values. entries() returns value-value pairs, which exists for consistency with Map's API so you can use the same iteration patterns for both.

Converting Between Set and Array

DirectionCode
Array → Setnew Set(array)
Set → Array[...set] or Array.from(set)

These conversions are fast and common. You can go back and forth as needed, using Set when you need uniqueness checks and Array when you need indexed access or array methods.

Set Composition Methods

Modern JavaScript (ES2024+) provides native set operation methods, available in all current browsers and Node.js since mid-2024. These accept any set-like object (an object with size, has(), and keys()):

javascriptjavascript
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
 
console.log(a.union(b));        // Set {1, 2, 3, 4, 5, 6}
console.log(a.intersection(b)); // Set {3, 4}
console.log(a.difference(b));   // Set {1, 2}
console.log(a.isSubsetOf(b));   // false

Before these built-in methods, you would implement set operations manually using filter and spread. The native methods are cleaner and more performant. For more context on how Set compares to arrays for these patterns, see the article on /javascript/set-vs-array-in-javascript-complete-guide.

Practical Use: Tracking Seen Items

A common pattern is using a Set to track which items have already been processed:

javascriptjavascript
const processed = new Set();
 
function handleItem(id, data) {
  if (processed.has(id)) {
    return; // Skip duplicates
  }
  processed.add(id);
  // ... process the data
}

This is cleaner than using an array with includes() because has() is faster on large collections and the intent is clearer.

Value Equality

Set uses the SameValueZero algorithm, meaning NaN is treated as equal to NaN, even though NaN !== NaN:

javascriptjavascript
const s = new Set();
s.add(NaN);
s.add(NaN);
 
console.log(s.size); // 1 (not 2)
console.log(s.has(NaN)); // true

Object values follow a different rule than primitives, since equality is checked by reference, not by the values inside the object:

javascriptjavascript
const s = new Set();
s.add({ id: 1 });
s.add({ id: 1 });
 
console.log(s.size); // 2 (different object references)

Common Mistake: Set Has No Index Access

A Set has no concept of position, only membership, so bracket notation with a number does not do what an array user would expect. Unlike arrays, you cannot access a Set element by position:

javascriptjavascript
const s = new Set(["a", "b", "c"]);
 
// Wrong -- Sets do not support index access
// console.log(s[0]); // undefined
 
// Correct -- convert to array first if you need indexing
console.log([...s][0]); // "a"

Set is designed for uniqueness and membership, not positional access. If you need both, convert to an array when you need indexed operations. For removing duplicates from arrays, combining Set with the spread operator as shown here is the standard approach covered in more detail in the article on /javascript/removing-duplicates-from-arrays-in-javascript-guide.

Rune AI

Rune AI

Key Insights

  • A Set stores unique values of any type -- duplicates are silently ignored.
  • Use add() to insert, delete() to remove, and has() to check membership.
  • The size property gives the count, and iteration preserves insertion order.
  • Convert between Set and Array with the constructor and spread operator.
  • Modern Set composition methods (union, intersection, difference) work across Set-like objects.
RunePowered by Rune AI

Frequently Asked Questions

What is a Set in JavaScript?

A Set is a collection of unique values of any type. Each value can only appear once in a Set. It is similar to an array but automatically enforces uniqueness and provides fast membership checking with has().

How do I remove duplicates from an array using Set?

Pass the array to the Set constructor, then spread it back into an array: const unique = [...new Set(array)]. This is the simplest one-liner for deduplication.

Does Set preserve insertion order?

Yes. Set iterates elements in the order they were first inserted. This is guaranteed by the specification, just like Map.

Conclusion

Set is the right collection when you need uniqueness guarantees without manual checks. Use it for deduplication, membership testing, and tracking collections of unique items. The built-in methods and iteration support make it a clean replacement for array-based workarounds.