JavaScript Set Methods

JavaScript's Set object lets you store unique values of any type—whether primitive values or object references. It provides useful methods to add, delete, check, and iterate through elements efficiently. Understanding these methods is crucial when working with collections of unique items.

Here are some commonly used Set methods:

  • add(): Adds a new element to a Set.
  • delete(): Removes a specified element from a Set.
  • has(): Returns true if a value exists in a Set.
  • clear(): Removes all elements from a Set.
  • forEach(): Executes a function for each value in the Set.
  • size: A property that returns the number of elements in a Set.
  • values(): Returns a new iterator object containing the values in a Set.
  • keys(): An alias for values()—included for compatibility with Map.
  • entries(): Returns a new iterator with [value, value] pairs for each element in a Set.


Adding Values to a Set

Unlike arrays, a Set in JavaScript automatically ensures that all its values are unique. You can use the add() method to insert values into a set. If the value already exists, the set remains unchanged.

  • add() – Adds a new element to the set if it doesn’t already exist.

Example 1: Using add() to Insert Values

The add() method inserts a value into the set. If the value already exists, it will not be added again—preserving uniqueness automatically.

javascript
const fruits = new Set();
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // Duplicate, won't be added

console.log(fruits);

How It Works:

  • fruits: A new Set is initialized empty.
  • add("apple"): Adds "apple" to the set.
  • add("banana"): Adds "banana" to the set.
  • add("apple"): Attempt to add a duplicate value is ignored.
  • console.log(fruits): Displays a Set containing only unique values.

Output

Set(2) { 'apple', 'banana' }

Deleting Values from a Set

JavaScript provides two main ways to remove values from a Set: removing a specific value with delete(), or clearing all values with clear(). These methods allow you to manage the contents of a set efficiently.

  • delete() – Removes a specific element from the set.
  • clear() – Removes all elements from the set.

Example 1: Using delete() to Remove a Specific Value

The delete() method removes a specific value from a set. If the value is found and removed, it returns true. Otherwise, it returns false.

javascript
const animals = new Set(["cat", "dog", "rabbit"]);
animals.delete("dog");

console.log(animals);

How It Works:

  • animals: The initial set contains three animal names.
  • delete("dog"): Removes "dog" from the set.
  • console.log(animals): Displays the set without the removed value.

Output

Set(2) { 'cat', 'rabbit' }

Example 2: Using clear() to Remove All Values

The clear() method removes all elements from the set, leaving it empty.

javascript
const numbers = new Set([1, 2, 3]);
numbers.clear();

console.log(numbers);

How It Works:

  • numbers: The original set contains three numbers.
  • clear(): Removes all values from the set.
  • console.log(numbers): Displays an empty set.

Output

Set(0) {}

Checking Values in a Set

To determine whether a specific value exists in a Set, you can use the has() method. This method returns a boolean indicating whether the value is present.

  • has() – Returns true if the value exists in the set, otherwise false.

Example: Using has() to Check for a Value

The has() method checks for the presence of a specific element. It's a fast and efficient way to test membership in a set.

javascript
const cities = new Set(["New York", "London", "Paris"]);

console.log(cities.has("London"));  // true
console.log(cities.has("Tokyo"));   // false

How It Works:

  • cities: A set containing three city names.
  • has("London"): Returns true because "London" exists in the set.
  • has("Tokyo"): Returns false because "Tokyo" is not in the set.

Output

true
false

Set Size

You can determine how many unique values are stored in a Set using the size property. This is similar to the length property of arrays.

  • size – Returns the number of unique elements in the set.

Example 1: Checking the Size of a Set

After adding elements to a set, you can use the size property to check how many unique items it contains.

javascript
const colors = new Set();
colors.add("red");
colors.add("green");
colors.add("red"); // Duplicate, won't be added

console.log(colors.size);

How It Works:

  • colors: A new Set is initialized empty.
  • add("red"): Adds "red" to the set.
  • add("green"): Adds "green" to the set.
  • add("red"): Duplicate value is ignored.
  • colors.size: Returns the number of unique values in the set.

Output

2

Iterating a Set

JavaScript Set objects are iterable, which means you can loop through their elements using built-in methods like forEach(), values(), and entries(). Each method gives you a way to access set elements, often used for processing or displaying data.

  • forEach() – Executes a provided function once for each value.
  • values() – Returns an iterator containing the values in the set.
  • entries() – Returns an iterator with [value, value] pairs (for compatibility with Map).

Example 1: Using forEach() to Loop Through a Set

The forEach() method allows you to execute a callback for each item in the set.

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

numbers.forEach((value) => {
  console.log(value);
});

Output

1
2
3

Example 2: Using values() to Get an Iterator

The values() method returns an iterator object containing all the values in the set.

javascript
const letters = new Set(["a", "b", "c"]);

for (const value of letters.values()) {
  console.log(value);
}

Output

a
b
c

Example 3: Using entries() to Access [value, value] Pairs

The entries() method returns an iterator of [value, value] pairs. This behavior mirrors that of Map for compatibility, even though sets don’t have keys.

javascript
const animals = new Set(["cat", "dog"]);

for (const entry of animals.entries()) {
  console.log(entry);
}

Output

[ 'cat', 'cat' ]
[ 'dog', 'dog' ]

Frequently Asked Questions

What are the common methods available on a JavaScript Set?

Common Set methods include add(), delete(), has(), clear(), forEach(), values(), and entries().


How does the add() method work on a Set?

The add() method inserts a new element only if it doesn’t already exist in the Set, ensuring all values remain unique.


How do I remove elements from a Set?

Use delete() to remove a specific element, or clear() to remove all elements from the Set at once.


How can I check if a Set contains a specific element?

The has() method returns true if the Set contains the element, otherwise false.


How can I iterate over the elements of a Set?

You can use forEach() to run a function on each element, or use values() and entries() to get iterators for looping.



What's Next?

Up next: JavaScript WeakMaps – a special kind of map that allows object keys and offers better memory management for temporary data.