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.
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.
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value of the element to remove from the Set. |
Set.delete() returns value of type boolean
.
In JavaScript, we can use the delete()
method to remove a specific element from a Set object.
For example,
letters
with initial values 'a', 'b', and 'c'.delete()
method to remove the value 'b' from the letters
Set.letters
Set to the console using console.log()
.const letters = new Set(['a', 'b', 'c']);
letters.delete('b');
console.log(letters);
Set { 'a', 'c' }
In JavaScript, using the delete()
method to remove an element that is not present in the Set will return false.
For example,
numbers
with initial values 1 and 2.delete()
method to remove the value 3 from the numbers
Set.delete()
method call and the numbers
Set to the console using console.log()
.const numbers = new Set([1, 2]);
const result = numbers.delete(3);
console.log(result); // false
console.log(numbers);
false Set { 1, 2 }
In JavaScript, we can use the delete()
method to remove an object from a Set object.
For example,
people
with initial objects representing two people.delete()
method to remove one of the person objects from the people
Set.people
Set to the console using console.log()
.const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const people = new Set([person1, person2]);
people.delete(person1);
console.log(people);
Set { { name: 'Jane' } }
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.