JavaScript set() method is a set method, which is used to add a new element to the set. The Set
object is a built-in data structure that represents an unordered collection of unique values. The syntax of the set()
method is as follows:
mySet.set(value);
JavaScript set() method example
A simple example code first creates a new Set
object called mySet
and add three values to it.
<!DOCTYPE html>
<html>
<body>
<script >
let mySet = new Set();
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
// duplicate value
mySet.add("apple");
console.log(mySet);
console.log(typeof(mySet))
</script>
</body>
</html>
Output:
If the value already exists in the set, the set()
method does nothing and returns the original Set
object.
JavaScript set() methods
Methods | Description |
---|---|
add() | Adds a new element to the set. If the element already exists in the set, the add() method does nothing. |
clear() | Removes all elements from the set. |
delete() | Removes the specified element from the set. Returns a boolean indicating whether the element was successfully removed or not. |
entries() | It returns an object of Set iterator that contains an array of [value, value] for each element. |
forEach() | It executes the specified function once for each value. |
has() | Returns a boolean indicating whether the specified element exists in the set. |
values() | Returns a new iterator object that contains the values in the set. |
Do comment if you have any doubts or suggestions on this JS method topic
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version