Open In App

JavaScript Set delete() Method

The delete() method in JavaScript Set deletes an element from the set and returns true if the element existed and was successfully deleted. Otherwise, it returns false if the element does not exist.

Syntax:

mySet.delete(value);

Parameters:

Return value: It will return true if the value was present in the set and false if the value did not exist after removing the element.

JavaScript Set delete() Method Examples

Example 1: Removing Elements from a Set with the delete() Method

This code creates a new set called myset and adds two elements (75 and 12) using the add() method. Then, it prints the modified set. After that, it uses the delete() method to remove 75 from the set and prints the set again.

// Create a new set using Set() constructor
let myset = new Set();

// Append new elements to the set
// using add() method
myset.add(75);
myset.add(12);

// Print the modified set
console.log(myset);

// As 75 exists, it will be removed 
// and it will return true
console.log(myset.delete(75));
console.log(myset);

Output
Set(2) { 75, 12 }
true
Set(1) { 12 }

Example 2: Deleting Non-Existent Elements from a Set with the delete() Method

The code initializes a Set, adds elements, attempts to delete a non-existent element (43), which returns false. The Set remains unchanged, containing [23, 12].

// Create a new set using Set() constructor
let myset = new Set();

// Append new elements to the set
// using add() method
myset.add(23);
myset.add(12);

// Print the modified set
console.log(myset);

// As 43 does not exist nothing will be 
// changed and it will return false
console.log(myset.delete(43));
console.log(myset);

Output
Set(2) { 23, 12 }
false
Set(2) { 23, 12 }

Supported Browsers:

We have a complete list of Javascript Set methods, to check those please go through this Sets in JavaScript article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.  

Article Tags :