Set and Map in JavaScript: A Close Look
Tags: javascript, set, map, webdev
Published: 2023-11-08 13:35:34

In the world of JavaScript, there are several ways to handle and organize data, with arrays and objects being the most popular. However, ES6 (the sixth edition of the ECMAScript standard) introduced two useful data structures: `Set` and `Map`. These structures offer unique advantages that can be indispensable in specific scenarios.


&nbsp;

📌 **Table of Contents**

- [What is a Set?](#what-is-a-set)
  - [Creating a Set](#creating-a-set)
  - [Adding Values to a Set](#adding-values-to-a-set)
  - [Checking the Size of a Set](#checking-the-size-of-a-set)
  - [Checking if a Value Exists in a Set](#checking-if-a-value-exists-in-a-set)
  - [Removing Values](#removing-values)
  - [Iterating Over a Set](#iterating-over-a-set)
- [What is a Map?](#what-is-a-map)
  - [Creating a Map](#creating-a-map)
  - [Setting Key-Value Pairs](#setting-key-value-pairs)
  - [Getting Values](#getting-values)
  - [Checking the Size of a Map](#checking-the-size-of-a-map)
  - [Checking if a key Exists in a Map](#checking-if-a-key-exists-in-a-map)
  - [Removing Key-Value Pairs](#removing-key-value-pairs)
  - [Iterating Over a Map](#iterating-over-a-map)
- [Set vs. Array: When to Use Which?](#set-vs-array-when-to-use-which)
- [Map vs. Object: When to Use Which?](#map-vs-object-when-to-use-which)
- [Wrapping Up](#wrapping-up)





&nbsp;

## What is a Set?

&nbsp;


A `Set`  in JavaScript is a collection of values where each value must be unique. This means no duplicate values are allowed. The values can be of any type, and the order of values in the set does not matter.


&nbsp;

### Creating a Set

&nbsp;


Creating a set is simple. Use the `new` keyword followed by `Set()`.

```javascript
let mySet = new Set()

// console.log(mySet) 
// Output: Set(0) {}
```

&nbsp;

### Adding Values to a Set

&nbsp;

We can add values to a set using the `add` method:

```javascript
mySet.add(1)
mySet.add(5)
mySet.add('JavaScript')

// console.log(mySet) 
// Output: Set(3) { 1, 5, 'JavaScript' }
```

&nbsp;

### Checking the Size of a Set

&nbsp;

To check how many elements are in a Set, use the `size` property:

```javascript
console.log(mySet.size) // Output: 3
```

&nbsp;

### Checking if a Value Exists in a Set

&nbsp;

To check if a value is in a Set, use the `has` method:

```javascript
console.log(mySet.has(1)) // Output: true
console.log(mySet.has(2)) // Output: false
```

&nbsp;

### Removing Values

&nbsp;

Remove a specific element with the `delete` method:

```javascript
mySet.delete(5)
```

Or clear the entire Set with the `clear` method:

```javascript
mySet.clear()
```

&nbsp;

### Iterating Over a Set

&nbsp;

We can iterate over the values of a Set using `for...of` loop:

```javascript
for (let item of mySet) {
  console.log(item)
}
```

Or using `forEach` method:

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

&nbsp;

## What is a Map?

&nbsp;

A `Map` is a collection of key-value pairs, similar to an object, but with a few key differences. In a `Map`, keys can be of any data type, not just strings or Symbols. Also, maps maintain the order of insertion, which isn't guaranteed in plain objects.


&nbsp;

### Creating a Map

&nbsp;

To create a Map, we can use the `new` keyword, optionally passing an array of key-value pairs:

```javascript
let myMap = new Map()

// console.log(myMap) 
// Output: Map(0) {}
```


&nbsp;

### Setting Key-Value Pairs

&nbsp;

Use the `set` method to add key-value pairs to the Map:

```javascript
myMap.set('name', 'JavaScript')
myMap.set(1, 'ES6')
myMap.set(true, 'boolean')

// console.log(myMap) 
// Output: Map(3) { 'name' => 'JavaScript', 1 => 'ES6', true => 'boolean' }
```

&nbsp;

### Getting Values

&nbsp;

Retrieve a value by key using the `get` method:

```javascript
console.log(myMap.get('name')) // Output: 'JavaScript'
```

&nbsp;

### Checking the Size of a Map

&nbsp;

Similar to Set, Map have a `size` property:

```javascript
console.log(myMap.size) // Output: 3
```

&nbsp;

### Checking if a key Exists in a Map

&nbsp;

Check for the existence of a key using `has`:

```javascript
console.log(myMap.has('name')) // Output: true
```

&nbsp;

### Removing Key-Value Pairs 

&nbsp;

Remove a specific key-value pair with the `delete` method:

```javascript
myMap.delete('name')
```

Or clear the entire Map with the `clear` method:

```javascript
myMap.clear()
```

&nbsp;

### Iterating Over a Map

&nbsp;

Iterate through a Map's keys, values, or entries with the `keys`, `values`, and `entries` methods, respectively:

```javascript
for (let key of myMap.keys()) {
  console.log(key)
}

for (let value of myMap.values()) {
  console.log(value)
}

for (let [key, value] of myMap.entries()) {
  console.log(key, value)
}
```

We can also use the `forEach` method:

```javascript
myMap.forEach((value, key) => {
  console.log(key, value);
})
```


&nbsp;

## Set vs. Array: When to Use Which?

&nbsp;

Understanding when to use a `Set` instead of an Array can be crucial for both the performance and clarity of our code. While both can store collections of values, they serve different purposes.

&nbsp;

**Uniqueness**

If our primary concern is to prevent duplicate values, a `Set` automatically ensures that all elements are unique. With an Array, we would have to manually check for duplicates before adding a new element.

&nbsp;

**Performance**

When it comes to performance, especially for large collections of data, `Set` is more performant for checking the existence of an element within it. This is because `Set` is implemented with efficient data structures under the hood that allow for faster lookup.

&nbsp;

## Map vs. Object:  When to Use Which?

&nbsp;

While `Map` and `Object` in JavaScript can appear to serve similar functions as collections of key-value pairs, there are significant differences that could affect which one we should use.

&nbsp;

**Key Flexibility**

`Map` accepts keys of any data type, whereas an `Object` only accepts Strings and Symbols as keys.

&nbsp;

**Iteration Order**

`Map` maintains the order of elements as they were inserted, while the order of keys in a plain object is not guaranteed.


&nbsp;

**Size Determination**

&nbsp;

A `Map` directly provides the `size` property, making it easy to determine the number of key-value pairs. With an `Object`, we would typically use `Object.keys(obj).length`, which is less direct.


&nbsp;

**Performance**


For frequent additions and removals of key-value pairs, `Map` is more performant than using an `Object`.




&nbsp;

## Wrapping Up

&nbsp;

Both `Set` and `Map` are robust constructs in JavaScript that can greatly enhance the way we work with collections of data. With the knowledge of how to utilize these structures, we'll be able to write cleaner, more efficient code.






&nbsp;

![rich-text-editor-for-react npm package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scz09ynfwbdvqflj9ssh.png)
>[Demo](https://rich-text-editor-for-react.rasaf-ibrahim.com) | [Documentation](https://docs.rich-text-editor-for-react.rasaf-ibrahim.com)