JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Set Methods

8 April 2025 | Category:

JavaScript Set objects come with built-in methods that help you manage unique collections of values.

A Set ensures no duplicates, and you can perform various operations like adding, removing, and checking values.


âś… List of Common Set Methods

MethodDescription
add(value)Adds a new value
delete(value)Removes a specific value
has(value)Checks if a value exists
clear()Removes all values from the Set
values()Returns an iterator of Set values
forEach(callback)Loops through each value in the Set
sizeReturns the number of values (property)

🔹 add(value)

Adds a new unique value to the Set.

const items = new Set();
items.add("pen");
items.add("book");
items.add("pen"); // duplicate - ignored

console.log(items); // Set(2) { "pen", "book" }

🔹 delete(value)

Removes a value from the Set.

items.delete("pen");

console.log(items); // Set(1) { "book" }

🔹 has(value)

Checks if a value exists in the Set.

console.log(items.has("book"));  // true
console.log(items.has("pen"));   // false

🔹 clear()

Deletes all elements in the Set.

items.clear();

console.log(items); // Set(0) {}

🔹 values() or keys()

Returns an iterator of the Set’s values.

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

for (let letter of letters.values()) {
  console.log(letter);
}

Note: keys() is an alias for values() in Set (for consistency with Map).


🔹 forEach(callback)

Loops through each value in the Set.

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

🔹 .size Property

Gives the total number of values in the Set.

console.log(letters.size); // 3

đź§ľ Quick Example: All Methods in One

const numbers = new Set();

numbers.add(1);
numbers.add(2);
numbers.add(3);

console.log(numbers.has(2));   // true
numbers.delete(3);
console.log(numbers.size);     // 2

numbers.forEach(num => console.log(num)); // 1 2

numbers.clear();
console.log(numbers.size);     // 0

âś… Summary Table

Method / PropertyPurpose
add()Add a value
delete()Delete a specific value
has()Check if value exists
clear()Remove all values
values()Get iterator of values
forEach()Loop through values
sizeGet number of values (read-only)