![]() |
VOOZH | about |
A Set in JavaScript is used to store a unique collection of items, meaning no duplicates are allowed.
Set(3) { 10, 30, 40 }
Set(2) { 'gfg', 'geeks' }
Set(3) { 'f', 'o', 'd' }
Set(0) {}
JavaScript’s Set object comes with several built-in methods to add, remove, check, and iterate over values. Below are the most commonly used methods with syntax and examples.
Adds the new element with a specified value at the end of the Set object.
Syntax :
mySet.add(value);Example : In this example, we have added two numbers 23 and 12 into the set.
Set(2) { 23, 12 }
Set.delete() :
deletes an element with the specified value from the Set object.
Syntax :
mySet.delete(value);Example : Removing Elements from a Set with the delete() Method.
Set(2) { 75, 12 }
true
Set(1) { 12 }
Set.clear() :
The Set clear() method in JavaScript is used for the removal of all the elements from a set and making it empty.
Syntax:
mySet.clear();Example : Emptying set using Set clear() method.
Set(1) { 23 }
1
0
Set.entries() :
Returns an iterator object which contains an array having the entries of the set, in the insertion order.
Syntax :
mySet.entries()Example :
[ 'California', 'California' ] [ 'Seattle', 'Seattle' ] [ 'Chicago', 'Chicago' ]
Set.has() :
Returns true if the specified value is present in the Set object.
Syntax :
mySet.has(value);Example : In this example, we have used sethas() method.
true
Set.values() :
Returns all the values from the Set in the same insertion order.
Syntax:
mySet.values()Example :
California Seattle Chicago
Set.keys() :
Also returns all the values from the Set in the insertion order.
Syntax :
keys()Example : In this example, we will see the use of keys in the set.
[Set Iterator] { 'America', 'England', 'Chicago' }
Set.forEach() :
executes the given function once for every element in the Set, in the insertion order.
Syntax :
forEach(function(value, key, set) {
/* ... */
}, thisArg)
Example : In this example, we will see the use of the forEach() method.
s[Chicago] = Chicago s[California] = California s[undefined] = undefined