JavaScript Sets

About JavaScript Set

JavaScript set is a collection of unique values.

Set can store values of any data type.

Set does not allow duplicate value. While creating a set, it removes the duplicate value automatically.

Set doesn't have built-in methods for common set algebra operations like union, intersection, difference, and subset checking directly. But you can implement them.

Creating JavaScript Set

JavaScript sets can be created using Set() constructor.

Using Set Constructor:

An empty set can be created using set constructor 'new Set()' and elements can be added later to the empty set using add() method as demonstrated in the following example:

Example of Creating Set Using Set Constructor
Explanation of the code
  • let numSet = new Set();: This line creates an empty set using set constructor named ‘numSet’.
  • numSet.add(4); : This line adds an element (4) to the set 'numSet'.
  • console.log(numSet);: This line of code prints the 'numSet' in the console.

Using Set Constructor with Initial Values (Arrays or Iterables):

A set can be created by passing an array or any iterable objects as argument to the set constructor at the time of declaration.

Example of Creating Set from an Array
Explanation of the code
  • let numArray = [8, 4, 5, 2, 9];: This line creates an array of five numbers named ‘numArray’.
  • let numSet = new Set(numArray);: The ‘numArray' is passed as an argument to the set constructor. Thus it creates a set from an array.
  • console.log(numSet);: This line of code prints the 'numSet' in the console.
Example of Creating Set from a String
Explanation of the code
  • let myStr = "JavaScript";: This line declares a string named ‘myStry’.
  • let strSet = new Set(myStr);: The ‘myStry' is passed as an argument to the set constructor. Thus it creates a set from a string.
  • console.log(strSet);: This line of code prints the 'strSet' in the console.
Example of Creating a Set from a Map
Explanation of the code
  • const student = new Map([['name', 'John'], ['age', 24], ['program', 'CSE']]);: This line declares a map named ‘student’.
  • const studentSet = new Set(student.keys());: The keys of the ‘student' map is passed as an argument to the set constructor. Thus it creates a set from the keys of a map.
  • console.log(studentSet);: This line of code prints the 'studentSet' in the console.

Adding Elements(Values) to a Set

The add() method is used to add an element to a set as demonstrated in the following example:

Example of Adding Elements to a Set

Deleting Elements(Values) from a Set

The delete() method is used to delete an element from a set as demonstrated in the following example:

Example of Deleting Element from a Set

Size Property of Set

The size property returns the number of elements in a set as demonstrated in the following example:

Example of Size Property of Set

Iterating over a Set

A set is iterable and it can be iterated using for...of loop as demonstrated in the following example:

Example of Iterating Over a Set
Output of the above example
green
red
blue
                            

Methods of Set Object(Advanced Level)

1. add(value):

The add() method adds element of any data type to a set. It takes single argument of any data type.

Example of add() Method

2. delete(value):

The delete() method deletes/removes an element from a set and returns a Boolean value(on success: true, on failure: false).

Example of delete() Method

3. clear():

The clear() method clears all the values in the set.

Example of clear() Method

4. has(value):

The has() method checks whether the value exists in a set and returns a Boolean value.

Example of has() Method

5. keys():

The keys() method returns an iterator of values of a set.

Example of keys() Method
Output of the above example
green
red
blue
                            

6. values():

The values() method returns an iterator of values in a set.

Example of values() Method
Output of the above example
green
red
blue
                            

7. forEach(callback):

The forEach() method iterates over each element/value in a set, and runs a function for each one.

Example of forEach() Method
Output of the above example
4
16
64
                            
Explanation of the code
  • numberSet.forEach(function(number){console.log(number * number);});: Here forEach method iterates over the elements in the 'numberSet' and executes a function function(number){console.log(number * number) for each element. The function multiplies each element with itself and prints the product in the console.

7. entries():

The entries() method returns an iterator of values in a set in pairs.

Example of entries() Method
Output of the above example
green,green
red,red
blue,blue
                            

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Editor. Create more JavaScript sets and experiment with different set methods in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Editor
JavaScript Code Output