How do you create a new, empty Set in JavaScript?
const mySet = new Set();
How do you create a Set and initialize it with values from an existing array?
const myArray = [1, 2, 2, 3]; const mySet = new Set(myArray); // duplicates removed
How do you add a new element to a Set?
mySet.add(value); // e.g., mySet.add(5);
What happens if you try to add a duplicate value to a Set?
Duplicate values are ignored — Sets only store unique items.
How do you remove an element from a Set?
mySet.delete(value); // e.g., mySet.delete(2);
What is the return value of the delete() method in Sets?
true if removed successfully; false if element not found.
How do you check if a Set contains a specific value?
mySet.has(value); // e.g., mySet.has(7);
What is the return value of the has() method in Sets?
Boolean — true if the value exists, false otherwise.
How do you remove all elements from a Set?
mySet.clear();
How can you loop through all the values in a Set?
for (const value of mySet) { … } // or mySet.forEach(v => { … });
Does a Set have indexes like an array?
No — Sets have no indexes; you can’t access by position.
How do you convert a Set back into an array?
const myArray = […mySet];
How can you efficiently remove duplicates from an array using Sets?
const uniqueArray = […new Set(myArrayWithDuplicates)];
Are Sets guaranteed to maintain insertion order?
Yes — Sets preserve the order elements were added.
How do you perform a union of two Sets (all unique elements)?
function setUnion(setA, setB) {
const unionSet = new Set(setA);
for (const elem of setB) unionSet.add(elem);
return unionSet;
}
How do you perform an intersection of two Sets (common elements)?
function setIntersection(setA, setB) {
const intersectionSet = new Set();
for (const elem of setB)
if (setA.has(elem)) intersectionSet.add(elem);
return intersectionSet;
}
How do you perform a difference of two Sets (A minus B)?
function setDifference(setA, setB) {
const differenceSet = new Set(setA);
for (const elem of setB) differenceSet.delete(elem);
return differenceSet;
}