DEV Community

Cover image for What is a Set in JS?
_Khojiakbar_
_Khojiakbar_

Posted on

3 1 1 1 1

What is a Set in JS?

A Set is a collection of unique values. Unlike arrays, sets cannot have duplicate elements.

Basic Operations with Set

Creating a Set

You can create a new Set using the new Set() constructor. For example:

const uniqueNumbers = new Set([1, 2, 3, 3, 4]);
console.log(uniqueNumbers); // Output: Set(4) {1, 2, 3, 4}
Enter fullscreen mode Exit fullscreen mode

Funny-Serious Examples

Example 1: The Duplicate Party Crashers
Imagine you’re having a party, and you only want unique guests. But some guests try to sneak in twice!

const partyGuests = new Set();

partyGuests.add('Alice');
partyGuests.add('Bob');
partyGuests.add('Alice'); // Alice tries to sneak in again!

console.log(partyGuests); // Output: Set(2) {"Alice", "Bob"}
Enter fullscreen mode Exit fullscreen mode

Here, Alice tried to sneak in twice, but the Set only lets her in once.

Example 2: The Magic Hat Trick
You have a magic hat that only allows unique items to be stored. If you try to put the same item twice, it just won’t have it!

const magicHat = new Set();

magicHat.add('Rabbit');
magicHat.add('Dove');
magicHat.add('Rabbit'); // Another Rabbit tries to jump in!

console.log(magicHat); // Output: Set(2) {"Rabbit", "Dove"}
Enter fullscreen mode Exit fullscreen mode

The magic hat only contains one rabbit and one dove, despite the second rabbit trying to jump in.

Example 3: The Library of Unique Books
You run a library where each book must be unique. If someone tries to donate a book you already have, you politely decline.

const library = new Set(['1984', 'Brave New World', '1984']); // 1984 is already in the library!

console.log(library); // Output: Set(2) {"1984", "Brave New World"}
Enter fullscreen mode Exit fullscreen mode

Your library maintains its uniqueness by only keeping one copy of each book.

Useful Methods

Checking for a Member

Want to know if a particular guest is already at the party?

console.log(partyGuests.has('Alice')); // true
console.log(partyGuests.has('Charlie')); // false
Enter fullscreen mode Exit fullscreen mode

Removing a Member

Someone decides to leave the party early? No problem!

partyGuests.delete('Bob');
console.log(partyGuests); // Output: Set(1) {"Alice"}
Enter fullscreen mode Exit fullscreen mode

Clearing the Set

Party's over! Time to clear everyone out.

partyGuests.clear();
console.log(partyGuests); // Output: Set(0) {}
Enter fullscreen mode Exit fullscreen mode

Iterating Over a Set

Just like arrays, you can iterate over sets.

const animals = new Set(['Cat', 'Dog', 'Bird']);

for (const animal of animals) {
  console.log(animal); 
  // Output:
  // Cat
  // Dog
  // Bird
}
Enter fullscreen mode Exit fullscreen mode

Converting Between Sets and Arrays

You can convert a set to an array and vice versa.

const numberSet = new Set([1, 2, 3]);
const numberArray = [...numberSet]; // [1, 2, 3]

const arrayToSet = new Set(numberArray); // Set(3) {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

Why Use a Set?

Sets are particularly useful when you need to store a collection of unique items, and you want to avoid duplicates without having to manually check for them.

Summary

  • Unique Values: Sets store only unique values.
  • Basic Operations: You can add, delete, and check for values in a set.
  • Iterate: You can iterate over the values in a set.
  • Conversion: Easily convert between sets and arrays.

By using sets, you ensure that your collections remain unique and efficient, whether it’s a guest list for a party, items in a magic hat, or books in a library!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay