JavaScript Sets: Your Friendly Guide to Organized Data

Hello there, future JavaScript wizards! Today, we're going to embark on an exciting journey into the world of JavaScript Sets. Don't worry if you're new to programming – I'll be your trusty guide, and we'll explore this topic step by step. By the end of this tutorial, you'll be manipulating Sets like a pro!

JavaScript - Sets

What is a Set?

Before we dive into the code, let's talk about what a Set actually is. Imagine you have a bag of marbles, but this bag is special – it only allows one marble of each color. That's essentially what a Set is in JavaScript: a collection that can only contain unique values. No duplicates allowed!

Syntax: Creating a Set

Let's start with the basics. Here's how you create a new Set:

let mySet = new Set();

That's it! You've just created an empty Set. But what if you want to create a Set with some initial values? No problem:

let fruitSet = new Set(['apple', 'banana', 'orange']);

Now you have a Set with three fruits. Remember, even if you try to add another 'apple', it won't be included because Sets only keep unique values.

Parameters: What Can You Put in a Set?

Sets in JavaScript are quite flexible. You can add various types of values:

  • Numbers
  • Strings
  • Objects
  • Arrays
  • Even other Sets!

Let's see an example:

let mixedSet = new Set([1, 'two', {three: 3}, [4, 5]]);
console.log(mixedSet);

If you run this code, you'll see that our Set contains all these different types of values.

Examples: Playing with Sets

Now that we know the basics, let's have some fun with Sets!

Adding and Deleting Elements

let colorSet = new Set();

// Adding elements
colorSet.add('red');
colorSet.add('blue');
colorSet.add('green');

console.log(colorSet); // Output: Set(3) { 'red', 'blue', 'green' }

// Trying to add a duplicate
colorSet.add('red');
console.log(colorSet); // Output: Set(3) { 'red', 'blue', 'green' }

// Deleting an element
colorSet.delete('blue');
console.log(colorSet); // Output: Set(2) { 'red', 'green' }

As you can see, when we tried to add 'red' again, the Set remained unchanged. That's the beauty of Sets – they automatically handle duplicates for us!

Checking for Elements

Want to know if a Set contains a specific value? Use the has() method:

let animalSet = new Set(['dog', 'cat', 'bird']);

console.log(animalSet.has('dog')); // Output: true
console.log(animalSet.has('fish')); // Output: false

Size of a Set

To find out how many unique elements are in your Set, use the size property:

let numberSet = new Set([1, 2, 3, 4, 5, 5, 5]);
console.log(numberSet.size); // Output: 5

Even though we added three 5's, the Set only counts it once!

Mathematical Set Operations

Now, let's put on our math hats and look at some operations we can perform with Sets.

Union

A union combines two Sets, keeping all unique elements from both:

let set1 = new Set([1, 2, 3]);
let set2 = new Set([3, 4, 5]);

let unionSet = new Set([...set1, ...set2]);
console.log(unionSet); // Output: Set(5) { 1, 2, 3, 4, 5 }

Intersection

An intersection keeps only the elements that exist in both Sets:

let set1 = new Set([1, 2, 3, 4]);
let set2 = new Set([3, 4, 5, 6]);

let intersectionSet = new Set([...set1].filter(x => set2.has(x)));
console.log(intersectionSet); // Output: Set(2) { 3, 4 }

Difference

A difference keeps elements from the first Set that are not in the second Set:

let set1 = new Set([1, 2, 3, 4]);
let set2 = new Set([3, 4, 5, 6]);

let differenceSet = new Set([...set1].filter(x => !set2.has(x)));
console.log(differenceSet); // Output: Set(2) { 1, 2 }

JavaScript Set Reference

Here's a handy table of all the methods and properties we've discussed, plus a few more:

Method/Property Description
new Set() Creates a new Set
add(value) Adds a new element to the Set
delete(value) Removes an element from the Set
has(value) Returns true if the value exists in the Set
clear() Removes all elements from the Set
size Returns the number of elements in the Set
forEach(callback) Calls a function for each element in the Set
values() Returns an iterator with all the values in the Set
keys() Same as values()
entries() Returns an iterator with the [value, value] pairs from the Set

And there you have it, folks! You've just completed your crash course on JavaScript Sets. Remember, Sets are like those friends who always keep things unique and organized – they're great to have around when you're dealing with data that shouldn't have duplicates.

Practice creating and manipulating Sets, and soon you'll find yourself reaching for them naturally in your coding adventures. Who knows? Maybe you'll even start seeing Sets everywhere – like that one sock drawer where no two socks are the same!

Keep coding, stay curious, and remember: in the world of Sets, being unique is the name of the game!

Credits: Image by storyset