JavaScript Set

A Set is a built-in JavaScript object that allows you to store a collection of values where each value must be unique. Unlike an Array, a Set does not use indices (like `myArray[0]`); instead, it focuses on the existence of items within the collection.

Unique Values:

  • Sets store unique values, meaning each value can occur only once within a set.
  • Sets can hold any data type, including primitive values (numbers, strings, booleans) and complex objects (functions, arrays, or other objects).
Developer Tip: Use a Set whenever your primary goal is to check for the existence of an item or to ensure you don't have duplicates in your data.

No Duplicate Values:

  • When adding a value to a set that already exists, the set will not allow duplicates. It uses strict equality (similar to ===) to determine if a value is already present.
Common Mistake: Beginners often expect two different object literals with the same properties to be treated as duplicates. However, in JavaScript, {a: 1} === {a: 1} is false because they are different references in memory. Therefore, a Set will allow both objects to coexist.

Example: Creating a Set

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // Duplicate value, will be ignored

console.log(mySet); // Set(3) { 1, 2, 3 }

Size:

  • The size property returns the number of unique values in the set.
Watch Out: Unlike Arrays, which use the .length property, Sets use the .size property to count elements. Calling .length on a Set will return undefined.

Example: Size

console.log(mySet.size); // Output: 3

Iterability:

  • Sets are iterable, meaning you can use loop constructs like for...of to iterate over the values in the set.
  • Sets always maintain the insertion order. When you iterate over a Set, the elements are returned in the exact order they were first added.

Example: Iterating over a Set

for (let item of mySet) {
  console.log(item);
}
// Output: 1, 2, 3

Removing Values:

  • Use the delete() method to remove a specific value from the set. This method returns true if the element existed and was removed, and false otherwise.
  • Use the clear() method to remove all values from the set at once, resetting its size to zero.

Example: Removing Values

mySet.delete(2); // Removes the value 2 from the set. Returns true.
mySet.clear();   // Clears all values from the set. Size is now 0.
Best Practice: Use the has() method to check for membership. It is highly optimized and usually much faster than using Array.includes() for large datasets.

 

Key Points

  • Versatility: JavaScript Set stores unique values of any data type, from simple strings to complex nested objects.
  • Efficiency: Sets provide highly efficient methods for adding, removing, and checking for the presence of values (add, delete, has).
  • Deduplication: They are most commonly used for eliminating duplicates from arrays in a single line: const unique = [...new Set(myArray)];.
  • Iteration: Sets are iterable, making them easy to work with in loop constructs and with the spread operator.
Real-World Example: Imagine you are building a tagging system for a blog. A user might accidentally type the same tag twice. By using a Set to manage the tags before saving them to your database, you automatically ensure that every tag is unique without writing complex "if" checks.