HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Sets

A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type.


Essential Set Methods

Sets have built-in methods designed for managing unique collections.

Method Description
new Set() Creates a new Set
add() Adds a new element to the Set
delete() Removes an element from the Set
has() Returns true if a value exists in the Set
clear() Removes all elements from the Set
forEach() Invokes a callback for each element

Creating and Adding Values

You can create a Set by passing an array to the new Set() constructor, or by adding values later using add().

// Method 1: Literal from array
const letters = new Set(["a", "b", "c"]);

// Method 2: Adding manually
letters.add("d");
letters.add("e");
letters.add("a"); // This will be ignored (already exists)

Checking for Values (has)

The has() method is much faster than searching through an array. This makes Sets ideal for large collections where you frequently need to check for existence.

const colors = new Set(["Red", "Green", "Blue"]);

console.log(colors.has("Green")); // true
console.log(colors.has("Yellow")); // false

The size Property

Similar to length for arrays, Sets have a size property that tells you how many unique items are stored inside.

console.log(colors.size); // 3
Tip: You can quickly remove all duplicates from an array by converting it to a Set and then back to an array:
let unique = [...new Set(myArray)];

Key Points to Remember

  • A Set only stores unique values (no duplicates)
  • add() is used to insert items
  • has() is highly efficient for existence checks
  • Use the size property to count elements
  • Sets are iterables—they can be used with for...of and forEach()
  • Ideal for cleaning up data and maintaining lists of unique identifiers