Adding and Deleting Elements
You'll learn how to modify a Set by adding new values and removing existing ones, and what these operations return.
Core Operations
A Set provides two key methods for modification: add() and delete(). These methods let you change the Set's contents dynamically after creation.
The add() method inserts a new value into the Set. If the value already exists, the Set remains unchanged (remember, Sets only store unique values). The method returns the Set itself, enabling method chaining.
const colors = new Set();
colors.add('red');
colors.add('blue');
colors.add('green');
console.log(colors.size); // 3
colors.add('red'); // Already exists, no change
console.log(colors.size); // Still 3
The delete() method removes a specific value from the Set. It returns true if the value existed and was removed, or false if the value wasn't found.
const numbers = new Set([10, 20, 30]);
const removed = numbers.delete(20);
console.log(removed); // true
console.log(numbers.has(20)); // false
const notFound = numbers.delete(99);
console.log(notFound); // false
Chaining add() Calls
Since add() returns the Set, you can chain multiple additions together:
const fruits = new Set();
fruits.add('apple').add('banana').add('cherry');
console.log(fruits.size); // 3
Think of It Like This
Imagine a whiteboard with sticky notes. add() puts a new note up (or does nothing if that note already exists), then hands you back the whiteboard. delete() pulls off a specific note and tells you whether it found one to remove.
Key Takeaway: Use add() to insert values (returns the Set for chaining) and delete() to remove them (returns boolean indicating success).