Set in JavaScript (original) (raw)

Last Updated : 05 Mar, 2025

A Set in JavaScript is used to store a unique collection of items, meaning no duplicates are allowed.

// using an array let s1 = new Set([10, 30, 30, 40, 40]); console.log(s1); let s2 = new Set(["gfg", "gfg", "geeks"]); console.log(s2);

// using string let s3 = new Set("fooooooood"); console.log(s3);

// an empty set let s4 = new Set(); console.log(s4);

`

Output

Set(3) { 10, 30, 40 } Set(2) { 'gfg', 'geeks' } Set(3) { 'f', 'o', 'd' } Set(0) {}

How Set Internally Works in JavaScript

In JavaScript, hash tables are generally used to implement the property of unique values in the **Set data structure. The core property of a **Set is that it stores only unique values, and any duplicate values are automatically ignored.

**Process of Storing Data in a Hash Table

  1. **Iteration Over Values: The first step involves iterating over all the values passed in an array, which is then passed to the **Set constructor function. This iterator ensures that each value is processed individually.
  2. **Hashing with a Hash Function: A hash function, denoted as H(), is introduced. This function takes the value and converts it into a numerical index. The hash function’s purpose is to assign each unique value a specific index in the table.
  3. **Mapping Values to Hash Table: In this step, the respective indices for each value are mapped onto the hash table. For example, if the value 1 produces index 5 from the hash function, the value 1 will be stored at index 5 in memory.
  4. **Handling Duplicates: When a duplicate value is attempted to be added to the **Set, the hash function produces the same index for that value. The algorithm then checks whether that index already contains a value. If the index is already occupied, the new value is discarded, and the previous value is retained, ensuring the uniqueness of values in the **Set.

**Value Retrieval from the Hash Table

In a hash table, each unique value is stored at a separate index. To retrieve a value from the hash table, the index must be known beforehand. This allows **constant-time (O(1)) retrieval since the index is directly used to access the value.

Hash tables are considered optimized and fast for storing data, ensuring efficient management of the **Set data structure’s functionality, such as maintaining unique values and enabling quick lookups.

Key Characteristics of Sets

**Methods of Set in JavaScript

DSA Problems On Set In JavaScript.