JavaScript `Set` Object & Basic Operations
JavaScript Set Object & Basic Operations
While the previous lesson defined the abstract concept of a Set, JavaScript provides a built-in Set object that allows us to work with sets directly. Introduced in ES6, the Set object offers an efficient way to store unique values of any type, whether primitive values or object references.
1. Creating a JavaScript Set
You create a new Set instance using the new Set() constructor.
-
Concept:
- The constructor can take an optional iterable (like an
ArrayorString) whose elements will be added to the new Set. Any duplicate elements in the iterable will only be added once to the Set, demonstrating its uniqueness property.
- The constructor can take an optional iterable (like an
-
Syntax:
new Set(); new Set(iterable); -
Examples:
// 1. Creating an empty Set const mySet = new Set(); console.log(mySet); // Set(0) {} // 2. Creating a Set from an array (duplicates removed) const numbers = [1, 2, 3, 2, 4, 1, 5]; const uniqueNumbers = new Set(numbers); console.log(uniqueNumbers); // Set(5) { 1, 2, 3, 4, 5 } // 3. Creating a Set from a string (unique characters) const greeting = "hello world"; const uniqueChars = new Set(greeting); console.log(uniqueChars); // Set(8) { 'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd' } // 4. Set can hold mixed types, including objects (reference equality) const obj1 = { name: "Alice" }; const obj2 = { name: "Bob" }; const mixedSet = new Set([1, 'text', true, obj1, obj2, obj1]); console.log(mixedSet); // Set(5) { 1, 'text', true, { name: 'Alice' }, { name: 'Bob' } } // Note: obj1 is added only once, because it's the same object reference.
2. Basic Set Operations
The JavaScript Set object provides straightforward methods for common set operations.
2.1. Adding Elements: .add(value)
Adds a new value to the Set. If the value already exists, the Set is not modified.
- Time Complexity: Amortized
O(1)(average case),O(N)(worst case, due to potential hash collisions or resizing if implemented with hash tables). For practical purposes, consider itO(1). - Space Complexity:
O(1)for the new element.
const fruits = new Set();
fruits.add("apple");
fruits.add("banana");
console.log(fruits); // Set(2) { 'apple', 'banana' }
// Trying to add a duplicate has no effect
fruits.add("apple");
console.log(fruits); // Set(2) { 'apple', 'banana' } (still size 2)
fruits.add("orange");
console.log(fruits); // Set(3) { 'apple', 'banana', 'orange' }
2.2. Checking for Element Existence: .has(value)
Returns a boolean indicating whether a value is present in the Set.
- Time Complexity: Amortized
O(1)(average case),O(N)(worst case). PracticallyO(1). - Space Complexity:
O(1)
const colors = new Set(["red", "green", "blue"]);
console.log(colors.has("red")); // true
console.log(colors.has("yellow")); // false
2.3. Deleting Elements: .delete(value)
Removes a specified value from the Set. Returns true if the element was present and successfully removed, false otherwise.
- Time Complexity: Amortized
O(1)(average case),O(N)(worst case). PracticallyO(1). - Space Complexity:
O(1)(releasing memory for the element)
const veggies = new Set(["carrot", "broccoli", "spinach"]);
console.log(veggies.delete("broccoli")); // true (broccoli was removed)
console.log(veggies); // Set(2) { 'carrot', 'spinach' }
console.log(veggies.delete("potato")); // false (potato was not in the Set)
console.log(veggies); // Set(2) { 'carrot', 'spinach' } (no change)
2.4. Getting the Number of Elements: .size
A property (not a method) that returns the number of unique elements in the Set.
- Time Complexity:
O(1) - Space Complexity:
O(1)
const cities = new Set(["London", "Paris", "Tokyo"]);
console.log(cities.size); // 3
cities.add("London"); // No change, already exists
console.log(cities.size); // 3
cities.delete("Paris");
console.log(cities.size); // 2
2.5. Removing All Elements: .clear()
Removes all elements from the Set, making it empty.
- Time Complexity:
O(N)(must iterate and remove each element internally). - Space Complexity:
O(1)(releases all stored memory).
const dataSet = new Set([10, 20, 30]);
console.log(dataSet); // Set(3) { 10, 20, 30 }
console.log(dataSet.size); // 3
dataSet.clear();
console.log(dataSet); // Set(0) {}
console.log(dataSet.size); // 0
3. Iterating Over a Set
Sets are iterable, meaning you can use for...of loops, forEach, or spread syntax (...) with them.
- Time Complexity:
O(N)(to iterate through all elements). - Space Complexity:
O(1)for the iteration process (does not create a new large data structure).
const movies = new Set(["Inception", "Dune", "Arrival"]);
// Using for...of loop
console.log("--- Movies ---");
for (const movie of movies) {
console.log(movie);
}
// Output:
// Inception
// Dune
// Arrival
// Using forEach method
console.log("--- Movies with forEach ---");
movies.forEach(movie => {
console.log(`Watching: ${movie}`);
});
// Output:
// Watching: Inception
// Watching: Dune
// Watching: Arrival
// Converting Set to Array using spread operator
const movieArray = [...movies];
console.log(movieArray); // [ 'Inception', 'Dune', 'Arrival' ]
// Getting iterators (less common for basic use, but available)
const valuesIterator = movies.values();
console.log(valuesIterator.next().value); // Inception
const keysIterator = movies.keys(); // keys() and values() are the same for Sets
console.log(keysIterator.next().value); // Inception
const entriesIterator = movies.entries(); // Returns [value, value] pairs
console.log(entriesIterator.next().value); // [ 'Inception', 'Inception' ]
Note on Iteration Order in JavaScript Sets: While the abstract concept of a Set is unordered, the JavaScript
Setobject specifically maintains insertion order. This means elements will be iterated in the order they were added. However, it's crucial to distinguish this implementation detail from the abstract data type's definition, especially when discussing algorithms or theory where order is not guaranteed.

