Welcome to the Set Tutorial!
In this tutorial, we're going to explore the concept of Sets in JavaScript. You'll learn how to create a Set, add and remove elements, and use it to store unique tags associated with a blog post.
Step 1: Create a new Set
Open your index.js
file and add the following code:
let blogPostTags = new Set()
Run the code by clicking the "Run" button. You won't see any output in the console yet, but we've created an empty Set blogPostTags
.
What is a Set?
A Set is a collection of unique elements. Think of it like a container that stores only distinct values. In our example, we'll use a Set to store unique tags associated with a blog post.
Step 2: Add tags to the Set
Let's add some tags to our blogPostTags
Set:
blogPostTags.add("javascript")blogPostTags.add("web-development")blogPostTags.add("programming")blogPostTags.add("javascript") // try to add a duplicate tag
Run the code again. You'll notice that the duplicate tag 'javascript' is not added to the Set.
Why?
That's because Sets only store unique elements. When we try to add a duplicate tag, the Set ignores it, ensuring that we have a collection of distinct tags.
Step 3: Remove a tag from the Set
Let's remove the 'web-development' tag from the Set:
blogPostTags.delete("web-development")
Run the code again. The 'web-development' tag is now removed from the Set.
Step 4: Check if a tag is in the Set
Let's check if the 'programming' tag is in the Set:
console.log(blogPostTags.has("programming")) // Output: trueconsole.log(blogPostTags.has("react")) // Output: false
Run the code and observe the output in the console.
Step 5: Iterate over the Set
Let's iterate over the Set using a for...of
loop:
for (let tag of blogPostTags) { console.log(tag)}
Run the code and observe the output in the console. You should see the unique tags in the Set.
Real-World Example
Imagine you're building a blog platform, and you want to store unique tags associated with each blog post. Using a Set, you can ensure that each tag is only stored once, making it efficient and easy to manage.
You've learned about Sets!
Congratulations! You've learned how to create a Set, add and remove elements, and use it to store unique tags associated with a blog post.
What's Next?
In the next tutorial, we'll explore Classes in JavaScript. You'll learn how to define and use Classes to create objects with properties and methods.
Run the code again to see the output in the console.
Happy coding!
Tests