JavaScript Set delete() Method (original) (raw)
Last Updated : 12 Jul, 2024
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:
- ****value:**It is the value of the element that is to be deleted from the Set.
**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.
**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.
JavaScript `
// 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].
JavaScript `
// 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:
- Chrome
- Edge
- Firefox
- Opera
- Safari