Lesson 2
Understanding and Using JavaScript Sets
Introduction

I'm delighted to welcome you to our JavaScript Sets lesson! Remember, sets are like arrays or objects, except they can only hold unique elements. They're especially useful when you need to guarantee that elements in a collection appear only once.

In this lesson, you'll consolidate your knowledge of creating and operating on sets. You will learn about the advantages of using sets and how they enhance performance. Ready, Set, Go!

Creating and Manipulating Sets

Let's begin by creating a set in JavaScript. It can be done using the Set() constructor.

JavaScript
1// Creating a set and printing it 2let mySet = new Set([1, 2, 3, 4, 5, 5, 5]); // Duplicates will be omitted 3console.log(mySet); // Output: Set(5) { 1, 2, 3, 4, 5 }

JavaScript provides methods to manipulate sets, such as add(), has(), delete(), and clear().

JavaScript
1// Adding an element 2mySet.add(6); // mySet is now Set { 1, 2, 3, 4, 5, 6 } 3 4console.log(mySet.has(1)); // Output: true, as `mySet` includes an element 1 5 6// Removing an element 7mySet.delete(1); // mySet becomes Set { 2, 3, 4, 5, 6 } 8 9console.log(mySet.has(1)); // Output: false, as `mySet` doesn't include 1 anymore 10 11// Clearing the set 12mySet.clear(); // mySet becomes an empty set 13console.log(mySet); // Output: Set(0) {}
  • add(): Adds a specified element to the set.
  • has(): Checks if the specified element exists in the set.
  • delete(): Removes a specified element from the set.
  • clear(): Removes all elements from the set.
Set Operations

JavaScript does not directly provide built-in methods for operations such as union, intersection, and difference for sets, but they can be implemented using standard JavaScript.

JavaScript
1let set1 = new Set([1, 2, 3, 4]); // First set 2let set2 = new Set([3, 4, 5, 6]); // Second set 3 4// Set union 5let union = new Set([...set1, ...set2]); 6console.log(union); // Output: Set(6) { 1, 2, 3, 4, 5, 6 } 7 8// Set intersection 9let intersection = new Set([...set1].filter(x => set2.has(x))); 10console.log(intersection); // Output: Set(2) { 3, 4 } 11 12// Set difference 13let difference = new Set([...set1].filter(x => !set2.has(x))); 14console.log(difference); // Output: Set(2) { 1, 2 }
  • union: Combines elements from both sets, excluding any duplicates. In this case, the result is a set containing {1, 2, 3, 4, 5, 6}.
  • intersection: Returns a set with only the elements that are common to both sets. For these sets, the intersection is {3, 4}.
  • difference: Returns a set containing elements that are in the first set but not in the second set. Here, the result is {1, 2} for set1.
Performance Benefits of Sets

One of the key advantages of sets is their faster performance in membership tests, which results from their use of hash tables.

JavaScript
1let mySet = new Set(Array.from({length: 10000000}, (_, i) => i)); // A set of 10^6 elements 2console.time("Set"); 3console.log(mySet.has(9999999)); // Sets find the number swiftly 4console.timeEnd("Set"); 5 6let myArray = Array.from({length: 10000000}, (_, i) => i); // An array with the same elements and order 7console.time("Array"); 8console.log(myArray.includes(9999999)); // Arrays take longer to find the number 9console.timeEnd("Array");
  • Membership Test with Set: Thanks to hash tables, sets can check for membership in constant time, leading to quick lookup times. The time taken for checking membership in the set is remarkably low.
  • Membership Test with Array: Arrays require a linear search to check for membership, which results in longer lookup times as the array grows. The time taken for checking membership in the array is noticeably higher.
Lesson Summary

Congratulations! You've just explored creating and manipulating sets, performing set operations, and reaping the performance benefits of sets in JavaScript.

Remember, practice is key to solidifying your understanding. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.