Menu
Posted At Fri, Nov 10, 2023 2:16 PM

JavaScript Set

Listen | 2 min read

Table of Contents

1. Introduction to JavaScript Set
- What is a Set?
- Why Use Sets in JavaScript?
2. Creating a Set
- Syntax for Set Creation
- Adding Elements to a Set
3. Operations on Sets
- Checking the Size of a Set
- Iterating Through a Set
- Checking the Existence of an Element
4. Set Methods
- Adding and Deleting Elements
- Clearing a Set
- Converting Set to Array
5. Use Cases for Sets
- Removing Duplicates from Arrays
- Performing Set Operations
6. Limitations and Considerations
- Uniqueness in Set
- Type Coercion in Set

1. Introduction to JavaScript Set

- What is a Set?

In JavaScript, a Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references.

- Why Use Sets in JavaScript?

Sets are particularly useful when you need to deal with collections of unique values, eliminating the need for manual deduplication.

2. Creating a Set

- Syntax for Set Creation

let mySet = new Set();

- Adding Elements to a Set

mySet.add(1); 
mySet.add('Hello'); 
mySet.add({ key: 'value' });

3. Operations on Sets

- Checking the Size of a Set

console.log(mySet.size); // Output: 3

- Iterating Through a Set

mySet.forEach((value) => {
  console.log(value);
});

- Checking the Existence of an Element

console.log(mySet.has(1)); // Output: true

4. Set Methods

- Adding and Deleting Elements

mySet.add(42);
mySet.delete('Hello');

- Clearing a Set

mySet.clear();

- Converting Set to Array

let myArray = [...mySet]; 

5. Use Cases for Sets

- Removing Duplicates from Arrays

let arrayWithDuplicates = [1, 2, 3, 1, 2, 4];
let uniqueArray = [...new Set(arrayWithDuplicates)];

- Performing Set Operations

Sets support operations like union, intersection, and difference.

6. Limitations and Considerations

- Uniqueness in Set

While Sets ensure uniqueness, you need to be aware of potential pitfalls with object references.

- Type Coercion in Set

Sets use strict equality (===) for comparisons, which might lead to unexpected results with different types.

In conclusion, JavaScript Sets provide a powerful tool for managing collections of unique values efficiently. Understanding their operations and methods can significantly enhance your ability to work with distinct elements in your projects.

Next one is learning about JavaScript Weak Set.

Click this link! 👇

1356 1

Comments