JavaScript Set delete()
Syntax & Examples
Set.delete() method
The delete() method of the Set object in JavaScript removes the specified element from a Set object and returns a boolean indicating whether the element was successfully removed.
Syntax of Set.delete()
The syntax of Set.delete() method is:
setInstance.delete(value)This delete() method of Set removes the element associated with the value and returns a boolean asserting whether an element was successfully removed or not. Set.prototype.has(value) will return false afterwards.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
value | required | The value of the element to remove from the Set. |
Return Type
Set.delete() returns value of type boolean.
✐ Examples
1 Using delete() to remove an element from a Set
In JavaScript, we can use the delete() method to remove a specific element from a Set object.
For example,
- Create a new Set object
letterswith initial values 'a', 'b', and 'c'. - Use the
delete()method to remove the value 'b' from thelettersSet. - Log the
lettersSet to the console usingconsole.log().
JavaScript Program
const letters = new Set(['a', 'b', 'c']);
letters.delete('b');
console.log(letters);Output
Set { 'a', 'c' }2 Using delete() to attempt removing a non-existent element
In JavaScript, using the delete() method to remove an element that is not present in the Set will return false.
For example,
- Create a new Set object
numberswith initial values 1 and 2. - Attempt to use the
delete()method to remove the value 3 from thenumbersSet. - Log the result of the
delete()method call and thenumbersSet to the console usingconsole.log().
JavaScript Program
const numbers = new Set([1, 2]);
const result = numbers.delete(3);
console.log(result); // false
console.log(numbers);Output
false
Set { 1, 2 }3 Using delete() to remove an object from a Set
In JavaScript, we can use the delete() method to remove an object from a Set object.
For example,
- Create a new Set object
peoplewith initial objects representing two people. - Use the
delete()method to remove one of the person objects from thepeopleSet. - Log the
peopleSet to the console usingconsole.log().
JavaScript Program
const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const people = new Set([person1, person2]);
people.delete(person1);
console.log(people);Output
Set { { name: 'Jane' } }Summary
In this JavaScript tutorial, we learned about delete() method of Set: the syntax and few working examples with output and detailed explanation for each example.