What is the set.delete() method in JavaScript?

In JavaScript, the set.delete() function is used to remove a specific element from a set.

The image below shows a visual representation of the set.delete() function:

Representation of the set.delete() function

A set is a particular instance of a list in which all inputs are unique.

Note: If there are duplicates, the set will only keep the first instance. For example: {'Tom','Alsvin','Eddie','Tom'} will result in {'Tom','Alsvin','Eddie'}.

Syntax

set_name.delete(element)
// where the set_name is the name of the set.

Parameter

This function takes element, which represents the element that is to be removed as a parameter.

Return value

This function removes the element that is sent as a parameter from the set. It returns true if the element is present in the set. Otherwise, it returns false.

Code

The code below shows how to use the set.delete() function in JavaScript:

const set_1 = new Set(["Tom","Alsvin", "Eddie"]);
//set containing value before delete
console.log("set_1 elements before Delete: ",set_1);
//deleting element from set
console.log("Removing 'Eddie' from the set_1: ",set_1.delete("Eddie"))
//set containing value after delete
console.log("set_1 elements after Delete: ", set_1);
//trying to remove element not present in set
console.log("Removing 'Jack' from the set_1: ", set_1.delete("Jack"));

Explanation

  • Line 1: We create a set with three values {'Tom','Alsvin','Eddie'} and name it set_1.

  • Line 6: We delete an element Eddie from set_1 using the delete() method. It returns true.

  • Line 11: If we try to delete an element that is not present in the set, it will return false.

Free Resources