Set in JavaScript

Overview

Sets are a fundamental data structure introduced in ECMAScript 6 (ES6) that allow for the storage of unique items. Unlike arrays, sets automatically prevent the storage of duplicate elements, ensuring that each item is unique within the collection. Sets provide several methods for managing their elements, including:

  • add(value): Adds a new element with the given value to the set.
  • has(value): Checks if an element with the given value exists in the set.
  • size: Returns the number of elements in the set.

Creating a Set

To create a set, you use the Set constructor. You can initialize an empty set or create a set with an array of elements. When initializing with an array, the set will automatically ensure that all elements are unique, removing any duplicates.

// Creating an empty set
let mySet = new Set();

// Creating a set with initial values
let numberSet = new Set([1, 2, 3, 4, 5]);

Operations on Sets

Union of Sets

The union of two sets is an operation that combines the elements of both sets into a new set. This new set contains all unique elements from both original sets, effectively merging them without duplicates.

Intersection of Sets

The intersection of two sets results in a new set containing only the elements that are common to both sets. This operation filters out any elements that are not shared between the sets.

Differences of Sets

The difference between two sets is an operation that results in a new set containing elements that are present in one set but not in the other. This effectively filters out any elements that are common to both sets, leaving only the unique elements from the first set.

Historical Context

Before the introduction of sets in ES6, developers often had to mimic set behavior using standard objects. This involved manually ensuring that each key in the object was unique, which could be cumbersome and error-prone. The following listing provides a crude example of how sets were mimicked with objects:

Listing 9.19. Mimicking sets with objects