In JavaScript, a Set is a collection of unique values. You can add and remove elements from a Set using its built-in methods.
The delete()
method is used to remove an element from a Set.
Here’s an example of how to remove an element from a Set in JavaScript:
// Create a new Set
const mySet = new Set([1, 2, 3, 4]);
// Remove an element from the Set
mySet.delete(3);
// Print the Set
console.log(mySet);
// Output: Set { 1, 2, 4 }
In the above code, we create a new Set called mySet
with four elements. We then call the delete()
method on mySet
and pass in the value we want to remove, which is 3
. Finally, we print the updated Set to the console and see that the element 3
has been removed.
If the value passed to delete()
is not found in the Set, nothing happens and the Set remains unchanged.
For example:
// Create a new Set
const mySet = new Set([1, 2, 3, 4]);
// Try to remove an element that doesn't exist
mySet.delete(5);
// Print the Set
console.log(mySet);
// Output: Set { 1, 2, 3, 4 }
In the above code, we try to remove the value 5
from mySet
, but since 5
is not in the Set, nothing happens and the Set remains unchanged.
You can also remove all elements from a Set using the clear()
method.
For example:
// Create a new Set
const mySet = new Set([1, 2, 3, 4]);
// Clear the Set
mySet.clear();
// Print the Set
console.log(mySet);
// Output: Set {}
In the above code, we call the clear()
method on mySet
to remove all its elements. The Set is now empty, as shown in the console output.
It’s worth noting that the clear()
method does not return any value, so you can’t check what was removed from the Set.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.