Telerik blogs

Set objects in JavaScript are a collection of unique values, where each value can only occur once within the set. In this article, we’ll explore their purpose, how to use them and how they differ from other data structures.

When working with JavaScript, developers often encounter scenarios where they need to manage collections of unique values. While arrays and objects can handle such situations, the JavaScript Set object offers distinct advantages and functionalities that can simplify and optimize the handling of unique values.

In this article, we will delve into the concept of Set objects in JavaScript, their purpose and how they differ from other data structures like arrays or objects. Let’s dive in!

The Set Object

A Set object in JavaScript is a collection of unique values, where each value can only occur once within the set. It provides an efficient way to store, retrieve and manipulate distinct values without worrying about duplicates. Set objects allow any data type as values, including primitive types, objects and even other sets!

To create a new Set object, we can use the Set() constructor:

const set = new Set();

In the above code, we initialize an empty Set object named set. Alternatively, we can initialize a Set object with an iterable, such as an array, during its creation:

const set = new Set(["value1", "value2", "value3"]);

Working with Set Objects

Once a Set object has been created, we can utilize various methods provided by the Set prototype to manipulate its content.

Adding Values

To add a new value to a Set object, we can use the add() method. Here’s an example of adding two string values to the Set object.

const set = new Set();

set.add("value1");
set.add("value2");

console.log(set);
/* Output: Set(2) { 'value1', 'value2' } */

If a value already exists in the Set, the add() method will have no effect.

const set = new Set();

set.add("value1");
set.add("value2");
set.add("value1"); // Trying to add a duplicate value

console.log(set);
/* Output: Set(2) { 'value1', 'value2' } */

Since Set's only store unique values, attempting to add a duplicate value has no effect. The duplicate value is not added to the set, and the set remains unchanged. This is due to Set's uniqueness constraint—it ensures that each value in a Set is unique, and duplicate values are automatically ignored.

This uniqueness property makes Sets particularly useful in scenarios where you want to maintain a collection of distinct values and easily check for the presence of a specific value.

It’s important to note that two objects with the same properties and values will be considered distinct in a Set.

const set = new Set();

const obj1 = { name: "Adam", age: 30 };
const obj2 = { name: "Adam", age: 30 };

set.add(obj1);
set.add(obj2);

console.log(set);
/* Output: Set(2) { { name: 'Adam', age: 30 }, { name: 'Adam', age: 30 } } */

Despite obj1 and obj2 having identical properties and values, the uniqueness constraint of the Set is based on the value’s identity. Since each object is considered distinct, both objects are added to the Set.

Checking Value Existence

To check if a specific value exists in a Set object, we can use the has() method:

const set = new Set(["value1", "value2"]);

console.log(set.has("value1")); // Output: true
console.log(set.has("value3")); // Output: false

Removing Values

To remove a value from a Set object, we can use the delete() method:

const set = new Set(["value1", "value2"]);

set.delete("value1");

console.log(set);
/* Output: Set(1) { 'value2' } */

Getting the Size of a Set

To determine the number of values in a Set object, we can use the size property:

const set = new Set(["value1", "value2"]);

console.log(set.size); // Output: 2

Iterating over Values

Set objects provide convenient methods for iterating over their values like forEach() and values().

The forEach() method allows us to execute a callback function for each value in the Set:

const set = new Set(["value1", "value2"]);

set.forEach((value) => {
  console.log(value);
});
/*
    Output:
    'value1'
    'value2' 
*/

The values() method returns an iterable object containing the values of the Set, which we can iterate using a loop:

const set = new Set(["value1", "value2"]);

for (const value of set.values()) {
  console.log(value);
}
/*
    Output:
    'value1'
    'value2' 
*/

Set vs. Other Data Structures

While arrays and objects are commonly used for storing collections of values in JavaScript, Set objects offer several advantages in certain scenarios.

  • Set objects ensure that each value occurs only once within the set, automatically handling deduplication without extra effort.
  • Set objects maintain the insertion order of values, making it easier to iterate over them in the order of insertion.

Set vs. Map

In a previous article, we did a deep dive into the JavaScript Map object. While both Set and Map objects in JavaScript are designed to handle collections of data, they serve different purposes and exhibit distinct characteristics.

The primary purpose of a Set object is to store and manage a collection of unique values. It ensures that each value occurs only once within the set, automatically handling deduplication. On the other hand, a Map object focuses on key-value data storage and retrieval. It allows the association of values with specific keys, similar to a dictionary or an associative array.

Conclusion

Set objects are particularly useful when dealing with scenarios that require uniqueness or fast value existence checks. By leveraging the Set's built-in methods for adding, checking and removing values, developers can simplify their code and reduce the complexity of handling distinct values.

Moreover, the Set object ensures uniqueness, maintains insertion order and provides efficient value existence checks, which makes it a powerful tool in specific use cases.


About the Author

Hassan Djirdeh

Hassan is currently a senior frontend engineer at Doordash. Prior to Doordash, Hassan worked at Instacart and Shopify, where he helped build large production applications at-scale. Hassan is also a published author and course instructor and has helped thousands of students learn in-depth fronted engineering tools like React, Vue, TypeScript and GraphQL. Hassan’s non-work interests range widely and, when not in front of a computer screen, you can find him at the gym, going for walks or running through the six.

Related Posts

Comments

Comments are disabled in preview mode.