JavaScript · Chapter 35 of 55

JavaScript Sets

A `Set` is a built-in collection that stores unique values of any type — no duplicates are allowed. Sets remember insertion order and are great for filtering duplicate data.

You create a Set with `new Set()`, optionally passing an iterable like an array, and manage it with `add()`, `delete()`, and `has()`.

Creating and using Sets

`new Set([1, 2, 2, 3])` automatically removes the duplicate, resulting in a Set containing 1, 2, 3.

Set methods

`add(value)` inserts, `delete(value)` removes, `has(value)` checks membership, and `size` gives the count of elements.

Example 1 (javascript)
let nums = new Set([1, 2, 2, 3, 3]);
console.log(nums);
console.log(nums.size);
Output
Set(3) { 1, 2, 3 }
3

Duplicates are automatically removed when creating the Set.

Example 2 (javascript)
let arr = [1, 1, 2, 2, 3];
let unique = [...new Set(arr)];
console.log(unique);
Output
[1, 2, 3]

Converting to a Set and back to an array is a common way to deduplicate.

Key points

  • A Set stores only unique values.
  • `add()`, `delete()`, `has()` manage Set contents.
  • `size` gives the number of elements (not `length`).
  • Sets preserve insertion order.
💡 Note: Spreading a Set into an array `[...set]` is the standard trick to deduplicate array data.

📝 Quick Quiz

1. What is unique about a Set's contents?

2. Which property gives a Set's element count?

3. How do you convert a Set back to an array?