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

ParameterOptional/RequiredDescription
valuerequiredThe 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,

  1. Create a new Set object letters with initial values 'a', 'b', and 'c'.
  2. Use the delete() method to remove the value 'b' from the letters Set.
  3. Log the letters Set to the console using console.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,

  1. Create a new Set object numbers with initial values 1 and 2.
  2. Attempt to use the delete() method to remove the value 3 from the numbers Set.
  3. Log the result of the delete() method call and the numbers Set to the console using console.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,

  1. Create a new Set object people with initial objects representing two people.
  2. Use the delete() method to remove one of the person objects from the people Set.
  3. Log the people Set to the console using console.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.