Populating Sets: set.add()
The set.add()
method appends a new element to the Set. If the element already exists in the Set, add()
does nothing, maintaining the Set's uniqueness constraint.
Example 1: Adding a Single Element
// Add a single value to an existing Set.
const colors = new Set();
colors.add("red");
console.log(colors); // Output: Set(1) {'red'}
Explanation This shows the fundamental use of add()
to insert a unique value into a previously created Set.
Example 2: Adding Duplicate Elements (No Effect)
// Attempting to add a duplicate value has no effect.
const fruits = new Set(["apple", "banana"]);
fruits.add("apple"); // 'apple' is already present
console.log(fruits); // Output: Set(2) {'apple', 'banana'}
Explanation Adding an element that is already in the Set does not change the Set's content or size, highlighting its unique value property.
Example 3: Chaining add()
Calls
// Chain multiple .add() calls for concise population.
const animals = new Set();
animals.add("dog").add("cat").add("bird");
console.log(animals); // Output: Set(3) {'dog', 'cat', 'bird'}
Explanation The add()
method returns the Set itself, allowing for method chaining to add multiple elements efficiently in a single line.
Example 4: Adding Different Data Types
// Sets can store diverse data types.
const diverseSet = new Set();
diverseSet.add(10);
diverseSet.add("text");
diverseSet.add(true);
console.log(diverseSet); // Output: Set(3) {10, 'text', true}
Explanation This illustrates that add()
can incorporate values of any JavaScript data type, including numbers, strings, and booleans.
Example 5: Adding Objects (Reference Uniqueness)
// Objects are considered unique based on their reference, not their content.
const obj1 = { id: 1 };
const obj2 = { id: 2 };
const obj3 = { id: 1 }; // Different reference than obj1
const objectSet = new Set();
objectSet.add(obj1);
objectSet.add(obj2);
objectSet.add(obj3); // This is a new object, so it's added.
console.log(objectSet); // Output: Set(3) {{id: 1}, {id: 2}, {id: 1}}
Explanation When adding objects, a Set considers two objects unique if they have different memory references, even if their content is identical.
Example 6: Using forEach
with add()
to Populate from an Array
// Populate a Set by iterating over an array.
const itemsToAdd = ["itemA", "itemB", "itemA", "itemC"];
const shoppingList = new Set();
itemsToAdd.forEach((item) => shoppingList.add(item));
console.log(shoppingList); // Output: Set(3) {'itemA', 'itemB', 'itemC'}
Explanation This common pattern demonstrates using forEach
with add()
to systematically populate a Set from an existing array, ensuring only unique items are stored.
Example 7: Dynamic Population Based on Condition
// Add elements to a Set only if they meet a specific condition.
const temperatures = [25, 18, 30, 25, 20, 32];
const warmDays = new Set();
temperatures.forEach((temp) => {
if (temp >= 25) {
warmDays.add(temp);
}
});
console.log(warmDays); // Output: Set(3) {25, 30, 32}
Explanation This example shows how add()
can be used conditionally within a loop, adding elements to the Set only if they satisfy a given criteria, further refining the unique collection.