JavaScript Sets
In JavaScript, a Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references.
Sets are collections of values where each value must be unique, and they maintain insertion order of elements.
Example
// Creating a Set const mySet = new Set(); // Adding values to the Set mySet.add(1); mySet.add(2); mySet.add(3); mySet.add(1); // Adding a duplicate value, which will be ignored // Checking the size of the Set console.log("Size of the Set:", mySet.size); // Output: 3 // Checking if a value exists in the Set console.log("Contains 2?", mySet.has(2)); // Output: true console.log("Contains 4?", mySet.has(4)); // Output: false // Deleting a value from the Set mySet.delete(2); // Iterating over the Set console.log("Iterating over the Set:"); for (let item of mySet) { console.log(item); }
Essential Set Methods
Method | Description |
---|---|
new Set() | Creates a new Set |
add() | Adds a new element to the Set |
delete() | Removes an element from a Set |
has() | Returns true if a value exists in the Set |
forEach | Invokes a callback for each element in the Set |
values() | Returns an iterator with all the values in a Set |
The new set() Method
Example
// ["sumit","amit","anil","anish"] let set1 = new Set(["sumit","sumit","amit","anil","anish"]); // it contains 'f', 'o', 'd' let set2 = new Set("fooooooood"); // it contains [10, 20, 30, 40] let set3 = new Set([10, 20, 30, 30, 40, 40]); // it is an empty set let set4 = new Set();
The new add() Method
It adds the new element with a specified value at the end of the Set object.
Example
let set1 = new Set(); set1.add(10); set1.add(20); // As this method returns // the set object hence chaining // of add method can be done. set1.add(30).add(40).add(50); console.log(set1);
The new delete() Method
It deletes an element with the specified value from the Set object.
Example
let set1 = new Set("foooodiiiieee"); // deleting e from the set // it prints true console.log(set1.delete('e')); console.log(set1); // deleting an element which is // not in the set // prints false console.log(set1.delete('g'));
The new has() Method
It returns true if the specified value is present in the Set object.
Example
let set1 = new Set(); // adding element to the set set1.add(50); set1.add(30); console.log(set1.has(50)); console.log(set1.has(10));
The new values() Method
It returns all the values from the Set in the same insertion order.
Example
let set1 = new Set(); // adding element to the set set1.add(50); set1.add(30); set1.add(40); set1.add("Geeks"); set1.add("GFG"); // getting all the values let getValues = set1.values(); console.log(getValues); let getKeys = set1.keys(); console.log(getKeys);