JavaScript Sets
Table of Contents
JavaScript Set and Its Methods:
Introduction to Sets in JavaScript
A Set in JavaScript is a collection of unique values. Unlike arrays, a Set automatically removes duplicate entries. It can hold any type of value—primitive or object references.
Key Characteristics
- Unique values: A Set ensures that all elements are unique.
- Iterable: Sets are iterable, meaning you can loop over their values.
- No duplicates: Any attempt to add duplicate values is ignored.
- Unordered: Elements in a Set are not indexed and do not follow a specific order.
Example
let mySet = new Set([1, 2, 3, 4, 4, 5]);
console.log(mySet); // Output: Set {1, 2, 3, 4, 5}
In this example, the duplicate 4 is removed automatically.
Creating Sets
You can create a Set using the Set constructor, either with or without an iterable (like an array) as its input.
Creating an Empty Set
let emptySet = new Set();
Creating a Set from an Array
let setFromArray = new Set([10, 20, 30, 40]);
console.log(setFromArray); // Output: Set {10, 20, 30, 40}
Set Methods
JavaScript provides several methods for working with Sets, allowing you to manipulate and inspect the collection.
add()
The add() method adds a new element to the Set. If the element already exists, it is not added again.
Example:
let numbers = new Set();
numbers.add(1);
numbers.add(2);
numbers.add(2); // Duplicate, won't be added
console.log(numbers); // Output: Set {1, 2}
delete()
The delete() method removes a specific element from the Set and returns true if the element was successfully removed.
Example:
let colors = new Set(['Red', 'Green', 'Blue']);
colors.delete('Green');
console.log(colors); // Output: Set { 'Red', 'Blue' }
has()
The has() method checks if a particular element exists in the Set. It returns true if the element is found, otherwise false.
Example:
let cities = new Set(['New York', 'London']);
console.log(cities.has('London')); // Output: true
console.log(cities.has('Paris')); // Output: false
clear()
The clear() method removes all elements from the Set, making it empty.
Example:
let fruits = new Set(['Apple', 'Banana']);
fruits.clear();
console.log(fruits); // Output: Set {}
size
The size property returns the number of elements in the Set.
Example:
let fruits = new Set(['Apple', 'Banana', 'Mango']);
console.log(fruits.size); // Output: 3
Set Iteration Methods
Sets can be iterated over in various ways, thanks to the iterable nature of this data structure.
forEach()
The forEach() method executes a provided function once for each value in the Set.
Example:
let languages = new Set(['JavaScript', 'Python', 'C++']);
languages.forEach(lang => console.log(lang));
// Output:
// JavaScript
// Python
// C++
values()
The values() method returns a new iterator object containing all the values in the Set. It’s essentially the same as the keys() method, as Sets do not have keys.
Example:
let numbers = new Set([1, 2, 3]);
let valuesIterator = numbers.values();
console.log(valuesIterator.next().value); // Output: 1
entries()
The entries() method returns an iterator object with key-value pairs, where both the key and the value are the same for each entry.
Example:
let set = new Set(['a', 'b', 'c']);
for (let entry of set.entries()) {
console.log(entry);
}
// Output:
// ['a', 'a']
// ['b', 'b']
// ['c', 'c']
keys()
The keys() method returns the same iterator as values(). Since Sets don’t have keys, the method returns the values of the Set.
Example:
let set = new Set([100, 200, 300]);
for (let key of set.keys()) {
console.log(key); // Output: 100, 200, 300
}
Set Operations
While JavaScript’s Set object doesn’t include methods like union, intersection, or difference by default, you can implement them manually using the Set’s methods.
Union
To create a union of two sets (all unique elements from both sets), use the add() method.
Example:
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
let unionSet = new Set([...setA, ...setB]);
console.log(unionSet); // Output: Set {1, 2, 3, 4, 5}
Intersection
To create an intersection of two sets (common elements in both sets), use the has() method.
Example:
let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Output: Set {2, 3}
Difference
To find the difference of two sets (elements in set A but not in set B), use the has() method.
Example:
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
let difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Output: Set {1, 2}
WeakSet (Special Type of Set)
A WeakSet is a special type of Set that only holds objects and does not prevent them from being garbage collected. WeakSets have the following differences from Sets:
- Only accepts objects (not primitive values).
- WeakSet elements are not enumerable and cannot be iterated.
- Methods include add(), delete(), and has(), but not size, clear(), or iteration methods.
Example:
let ws = new WeakSet();
let obj = {};
ws.add(obj);
console.log(ws.has(obj)); // Output: true
Summary
- Sets in JavaScript are an efficient way to store unique values.
- They offer several useful methods to manipulate and retrieve data, making them an excellent tool when you need collections with no duplicates.
- Additionally, you can manually implement set operations such as union, intersection, and difference.
Discussion
Kalpesh Shewale
I am grateful to have completed my Full Stack Development with AI course at Apnaguru. The faculty's support and interactive classes helped me discover my potential and shape a positive future. Their guidance led to my successful placement, and I highly recommend this institute.
Kalpesh Shewale
I am grateful to have completed the Full Stack Development with AI course at Apnaguru. The faculty's dedicated support and hands-on approach during the classes enabled me to unlock my potential and shape a promising future. Their guidance helped me secure a placement with a good package. I highly recommend this course, and for those interested, I also suggest doing the offline version at the center for an enhanced learning experience.

Raveesh Rajput
Completing the Full Stack Development with AI course at Apnaguru was a game-changer for me. I secured an internship through this course, which gave me invaluable hands-on experience. I strongly recommend this course to anyone looking to break into the tech industry. For the best experience, I suggest attending the offline sessions at the center, where the interactive learning environment really enhances the overall experience.

swapnil shinde
Apnaguru’s Full Stack Development with AI course provided me with more than just knowledge—it opened doors to an internship that gave me real-world, hands-on experience. If you're serious about a career in tech, this course is a must. I highly recommend attending the offline sessions for the most immersive and interactive learning experience!
Kalpana Waghmare
I recently completed the Full Stack Developer with AI course on ApnaGuru, and I couldn’t be more impressed! The structure of the course, with well-organized topics and self-assessment MCQs after each section, really helped reinforce my learning. The assignments were particularly valuable, allowing me to apply what I learned in a practical way. Overall, it’s an excellent program that effectively combines full-stack development and AI concepts. Highly recommended for anyone looking to enhance their skills!
Completing the Full Stack Development with AI course at Apnaguru was a pivotal moment in my career. It not only deepened my understanding of cutting-edge technologies but also directly led to an internship that provided practical, real-world experience. If you're aiming to enter the tech field, this course is an excellent stepping stone. I especially recommend attending the in-person sessions at the center, where the dynamic, hands-on learning approach truly maximizes the benefits of the program.

Mahesh Bhosle
I completed the Full Stack Development course at Apnaguru, and it was a valuable experience. The focus on live assignments and projects gave me real-world insights, helping me apply my skills in a professional setting. The interactive live sessions, mock interviews, and question banks were excellent for job preparation. Apnaguru’s company-like environment also helped me get accustomed to real work dynamics. Overall, this course equipped me with the skills and confidence needed for a career in full-stack development. I highly recommend it to anyone seeking hands-on learning and industry relevance.
I recently completed the Full Stack course at ApnaGuru, and I’m genuinely impressed! The curriculum is well-structured, covering both front-end and back-end technologies comprehensively. The instructors are knowledgeable and provide hands-on experience through practical projects. The supportive community and resources available made learning enjoyable and engaging. Overall, it’s a great choice for anyone looking to kickstart a career in web development. Highly recommend!

Adarsh Ovhal
I recently participated in the Full Stack Development With AI Course program, and it has been incredibly beneficial. The guidance I received was tailored to my individual needs, thanks to their advanced use of AI tools. The Trainers were knowledgeable and supportive, helping me explore various educational and career paths. The resources and workshops provided were practical and insightful, making my decision-making process much clearer. Overall, I highly recommend this program to any student looking for IT Field and personalized career guidance!
Shirish Panchal
I’m currently pursuing the Full Stack Developer with AI course at ApnaGuru Training Center, and I'm impressed with what I've experienced so far. The curriculum is well-structured, covering key concepts in both front-end and back-end development, along with AI fundamentals. The instructors are knowledgeable and supportive, which makes it easy to engage and ask questions. I particularly appreciate the hands-on projects that help reinforce what I’m learning. While I’m still in the process of completing the course, I feel that I'm building a strong foundation for my future in tech. I would recommend ApnaGuru to anyone looking to explore full stack development with AI!
Apnaguru Training Center stands out as a top-notch institute for IT education. They provide a wide array of courses, including Full Stack Development, Java Full Stack, Python, Automation Testing, DevOps, and MERN/MEAN Stack, all designed to meet the demands of the modern tech industry.

Mahesh Bhosle
Apnaguru Training Center is a fantastic place for IT education! They offer a variety of courses, including Full Stack Development, Java Full Stack, and Python, all taught by knowledgeable instructors who are committed to student success. The curriculum is up-to-date and includes hands-on projects that enhance learning.
dandewar srikanth
I had an excellent experience with the full-stack web development program at APNAGURU. The instructor had in-depth knowledge of both frontend and backend technologies, which made the concepts easy to grasp. From working on HTML, CSS, JavaScript, and React for the frontend to Node.js and MongoDB for the backend, the learning curve was very smooth.