Explanation & Working of Set’s in JavaScript

Explanation & Working of Set’s in JavaScript

In JavaScript, managing collections of data is a fundamental task. While Arrays are the go-to choice for most developers, the Set object offers a specialized way to store data when uniqueness is a priority.

A Set is a built-in object that allows you to store unique values of any type, whether they are primitive values (like numbers or strings) or complex object references.

What Makes a Set Unique?

The defining characteristic of a Set is that a value may only occur once. If you try to add a value that already exists in the collection, the Set simply ignores it.

Value Equality

Sets use a specific algorithm to check for equality. It is mostly similar to the === operator, but with some key differences:

  • NaN: In a Set, NaN is considered equal to NaN, so you can only store one NaN value.
  • Objects: Different object instances are considered unique, even if they have the same properties.
  • 0 vs -0: Since ES2015, +0 and -0 are considered the same value in a Set.

Basic Operations

Using a Set is straightforward. Here are the core methods you’ll use:

const mySet = new Set();

// 1. Adding values
mySet.add(1);
mySet.add(5);
mySet.add(5); // Duplicate, will not be added
mySet.add('Hello');

// 2. Checking for existence
console.log(mySet.has(1)); // true
console.log(mySet.has(10)); // false

// 3. Checking the size
console.log(mySet.size); // 3

// 4. Deleting values
mySet.delete(5);

// 5. Clearing everything
mySet.clear();

Practical Use Case: Removing Duplicates from an Array

The most popular use for a Set is to quickly clean up an array that contains duplicate entries.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Iterating Over a Set

Sets maintain the insertion order, so when you iterate through them, elements are returned in the order they were added.

const fruitSet = new Set(['Apple', 'Banana', 'Orange']);

// Using for...of
for (let item of fruitSet) {
    console.log(item);
}

// Using forEach
fruitSet.forEach(value => {
    console.log(value);
});

Set vs. Array: When to use which?

  • Use an Array if you need ordered access by index, allow duplicates, or need to perform heavy data manipulation using methods like map or reduce.
  • Use a Set when you need to ensure that your collection contains no duplicate values or when you need to perform fast lookups using the .has() method.

Conclusion

The Set object is a powerful tool in the JavaScript developer’s toolkit. By enforcing uniqueness and offering high-performance lookups, it simplifies many common logic hurdles in web development.


Discover more from TCMHACK

Subscribe to get the latest posts sent to your email.

Tags:

Leave a Reply

Discover more from TCMHACK

Subscribe now to keep reading and get access to the full archive.

Continue reading