Parameters of Set Methods in JavaScript
JavaScript sets come equipped with several methods that each accept specific parameters, enabling a variety of operations on set elements. Understanding these parameters is crucial for effectively using sets in your projects.
Set.add(value)
This method takes a single parameter, value, which is the element you want to add to the set. The method checks if the value already exists in the set; if it does not, it adds the value, ensuring all elements remain unique.
let mySet = new Set();
mySet.add(10);
mySet.add("Hello");
Here, 10 and "Hello" are the parameters passed to the add method, each representing a value being added to the set.
Set.delete(value)
This method accepts one parameter, value, which is the element to be removed from the set. If the value is found in the set, it is removed, and the method returns true; otherwise, it returns false.
mySet.delete(10); // returns true if 10 is in the set and removed, false otherwise
Set.has(value)
Takes one parameter, value, and returns true if the value exists in the set, otherwise false. This is useful for checking the presence of an item in the set without modifying the set.
mySet.has("Hello"); // returns true if "Hello" is in the set
Return Values of Set Methods in JavaScript
Each method associated with JavaScript sets is designed to return specific values based on the operation performed. These return values provide immediate feedback about the outcome of method calls, which is crucial for effective debugging and flow control in programming.
Set.add(value)
Returns the Set object itself after adding the specified element. This allows for method chaining, where you can add multiple items in a single line of code by chaining the add method.
let mySet = new Set();
mySet.add(10).add("Hello").add(20); // Chaining the add method
In this example, the set mySet is being returned after each add call, allowing the chaining.
Set.delete(value)
Returns a boolean value—true if the element was successfully removed from the set; otherwise, false. This is helpful to know whether the operation altered the set.
mySet.delete("Hello"); // returns true if "Hello" was in the set and removed
Set.has(value)
Also returns a boolean value—true if the set contains the specified element, and false if it does not. This method is useful for conditionally executing code based on the presence of an item.
mySet.has(10); // returns true if 10 is in the set
Set.clear()
This method does not return a value. It simply clears all the items from the set, making it empty. It’s a straightforward way to reset the set to its initial state.
mySet.clear(); // clears the set
Examples of Set Methods in JavaScript
Using set methods effectively can make data handling more intuitive and efficient. Here are detailed examples of how each method works in JavaScript:
Using Set.add()
JavaScript
let mySet = new Set();
mySet.add(5);
mySet.add("text");
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(2) {5, "text"}
In this example, we create a new set and add a number and a string to it. The console.log shows the set containing these two different types of elements, demonstrating the versatility of sets.
Using Set.delete()
JavaScript
mySet.delete(5);
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(1) {"text"}
Here, we remove the number 5 from the set. The console.log confirms that 5 has been successfully removed, leaving only the string "text".
Using Set.has()
JavaScript
console.log(mySet.has("text"));
console.log(mySet.has(5));

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
These lines of code check for the presence of elements in the set. The first call returns true because "text" is still in the set, while the second returns false since 5 has been removed.
Using Set.clear()
JavaScript
mySet.clear();
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(0) {}
This operation clears all elements from the set. The console.log shows an empty set, indicating that all items have been successfully removed.
Properties of Set in JavaScript
JavaScript sets are characterized by several useful properties that make them ideal for various programming scenarios where unique items are essential. Here’s a closer look at these properties:
Uniqueness
The most fundamental property of a JavaScript Set is that all elements must be unique. This means no two elements in the set can be identical. When you try to add a duplicate element, the Set simply ignores it, ensuring that each element remains unique.
JavaScript
let mySet = new Set();
mySet.add("apple");
mySet.add("banana");
mySet.add("apple");
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(2) {"apple", "banana"}
In this example, although "apple" is added twice, it only appears once in the set.
No Index-based Access
Unlike arrays, sets do not provide index-based access to their elements. You cannot refer to an element by its position. This design supports the notion that the order of elements is irrelevant in a set.
let firstElement = mySet[0]; // This is not valid in JavaScript Sets
Attempting to access elements using indices like this would not work, emphasizing the non-ordered nature of set elements.
Size
The size property of a set returns the number of elements it contains. This is helpful for quickly determining how many unique items are in the set.
console.log(mySet.size);
Output:
2
Here, size tells us that there are two unique elements in mySet.
Methods of Set in JavaScript
JavaScript sets provide a variety of methods that enable you to manipulate and interact with the data they hold. Each method serves a specific function, from adding elements to querying the set’s contents. Here's an overview of some commonly used Set methods:
Set.add(value)
Adds a new element with the specified value to the set. If the element is already present, it won't be added again.
JavaScript
let mySet = new Set();
mySet.add("coffee");
mySet.add("tea");
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(2) {"coffee", "tea"}
This method is used to ensure each element in the set remains unique.
Set.delete(value)
Removes the specified element from the set. Returns true if the element was found and removed, otherwise false.
JavaScript
mySet.delete("tea");
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output
Set(1) {"coffee"}
It's useful for directly removing items without needing to recreate the set.
Set.has(value)
Returns true if the set contains the specified element, otherwise false. This method is helpful for checking the presence of an element before performing further operations.
JavaScript
console.log(mySet.has("coffee"));
console.log(mySet.has("tea"));

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
Set.clear()
Removes all elements from the set, leaving it empty. This method is useful for resetting the set without needing to create a new instance.
JavaScript
mySet.clear();
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(0) {}
Set.forEach(callbackFn)
Executes a provided function once for each value in the set, in insertion order. This method does not return a value.
JavaScript
mySet.add("coffee");
mySet.add("tea");
mySet.forEach(value => console.log(value));

You can also try this code with Online Javascript Compiler
Run Code
Output:
"coffee"
"tea"
forEach is used to perform operations or calculations on elements within the set.
Set Operations in JavaScript
Understanding and utilizing set operations is fundamental in many programming tasks, especially when dealing with collections of data where uniqueness is key. Here’s how you can use JavaScript sets to perform common set operations:
Union of Two Sets
This operation combines all unique elements from two sets into a new set.
JavaScript
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
let unionSet = new Set([...setA, ...setB]);
console.log(unionSet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(5) {1, 2, 3, 4, 5}
By spreading the elements of both setA and setB into a new set, you get a set containing all elements from both, with duplicates removed.
Intersection of Two Sets
This operation finds common elements between two sets.
JavaScript
let intersectionSet = new Set([...setA].filter(x => setB.has(x)));
console.log(intersectionSet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(1) {3}
This method uses the .filter() function to select elements from setA that are also present in setB.
Difference of Two Sets
This operation returns a new set with elements in one set that are not in the other.
JavaScript
let differenceSet = new Set([...setA].filter(x => !setB.has(x)));
console.log(differenceSet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(2) {1, 2}
Here, .filter() helps retrieve elements that are unique to setA by excluding those found in setB.
JavaScript Set Methods: Detailed Examples
To further enhance your understanding of how to use set operations in JavaScript, let's practice some specific methods:
JavaScript subSet() Method
While JavaScript's native Set object does not include a direct subSet() method, we can simulate this functionality by checking if every element of one set is contained within another. Here's how you can implement a subset check function:
JavaScript
function isSubset(setA, setB) {
for (let elem of setA) {
if (!setB.has(elem)) {
return false;
}
}
return true;
}
let setA = new Set([1, 2]);
let setB = new Set([1, 2, 3, 4]);
console.log(isSubset(setA, setB));

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
This function iterates through each element in setA and checks whether setB contains it. It returns true if all elements are present, confirming setA is a subset of setB.
JavaScript union() Method
To create a union of two sets, which includes all elements from both sets without duplication, you can use the following approach:
JavaScript
function union(setA, setB) {
let unionSet = new Set(setA);
for (let elem of setB) {
unionSet.add(elem);
}
return unionSet;
}
let setA = new Set([1, 2, 3]);
let setB = new Set([4, 3, 5]);
console.log(union(setA, setB));

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(5) {1, 2, 3, 4, 5}
This method efficiently combines the elements of both sets, ensuring each element is unique in the resulting set.
JavaScript difference() Method:
The difference between two sets can be found by subtracting the elements of one set from another:
JavaScript
function difference(setA, setB) {
return new Set([...setA].filter(x => !setB.has(x)));
}
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([3, 4, 5, 6]);
console.log(difference(setA, setB));

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(2) {1, 2}
This returns a new set containing elements that are only in setA and not in setB.
JavaScript intersection() Method:
To find elements that are present in both sets, the intersection can be calculated as follows:
JavaScript
function intersection(setA, setB) {
return new Set([...setA].filter(x => setB.has(x)));
}
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([3, 4, 5, 6]);
console.log(intersection(setA, setB));

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(2) {3, 4}
This method filters out elements in setA that are also found in setB, effectively calculating their intersection.
Frequently Asked Questions
Can a JavaScript set store different types of values?
Yes, a JavaScript set can hold a variety of data types, including numbers, strings, and objects. Each element in a set must be unique, but the type of elements can vary within the same set.
How does a JavaScript set handle NaN values?
JavaScript sets treat NaN (Not-a-Number) as equal to itself, even though NaN !== NaN in comparison operations. This means you can add NaN to a set, and it will only store one instance of NaN.
Is it possible to get an array from a JavaScript set?
Yes, you can convert a set into an array using the spread syntax or Array.from method.
Both methods provide a straightforward way to transition from a set's unique collection to a more flexible array format.
Conclusion
In this article, we have learned the fundamental aspects of JavaScript sets, including their properties, methods, and how to perform various operations such as union, intersection, difference, and subset checks. We practiced detailed examples of each method to understand their practical applications fully. Sets are a versatile and essential part of the JavaScript language, offering a unique way to handle data that ensures all elements are distinct. Whether you're managing collections of users, responses, or any data where uniqueness is key, JavaScript sets provide the tools you need to perform these tasks efficiently and effectively.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.