DEV Community

Cover image for Set and Map in JavaScript: A Close Look
Rasaf Ibrahim
Rasaf Ibrahim

Posted on

Set and Map in JavaScript: A Close Look

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.

 

📌 Table of Contents

 

What is a Set?

 

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.

 

Creating a Set

 

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

let mySet = new Set()

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

 

Adding Values to a Set

 

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

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

// console.log(mySet) 
// Output: Set(3) { 1, 5, 'JavaScript' }
Enter fullscreen mode Exit fullscreen mode

 

Checking the Size of a Set

 

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

console.log(mySet.size) // Output: 3
Enter fullscreen mode Exit fullscreen mode

 

Checking if a Value Exists in a Set

 

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

console.log(mySet.has(1)) // Output: true
console.log(mySet.has(2)) // Output: false
Enter fullscreen mode Exit fullscreen mode

 

Removing Values

 

Remove a specific element with the delete method:

mySet.delete(5)
Enter fullscreen mode Exit fullscreen mode

Or clear the entire Set with the clear method:

mySet.clear()
Enter fullscreen mode Exit fullscreen mode

 

Iterating Over a Set

 

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

for (let item of mySet) {
  console.log(item)
}
Enter fullscreen mode Exit fullscreen mode

Or using forEach method:

mySet.forEach((value) => {
  console.log(value)
})
Enter fullscreen mode Exit fullscreen mode

 

What is a Map?

 

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.

 

Creating a Map

 

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

let myMap = new Map()

// console.log(myMap) 
// Output: Map(0) {}
Enter fullscreen mode Exit fullscreen mode

 

Setting Key-Value Pairs

 

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

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

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

 

Getting Values

 

Retrieve a value by key using the get method:

console.log(myMap.get('name')) // Output: 'JavaScript'
Enter fullscreen mode Exit fullscreen mode

 

Checking the Size of a Map

 

Similar to Set, Map have a size property:

console.log(myMap.size) // Output: 3
Enter fullscreen mode Exit fullscreen mode

 

Checking if a key Exists in a Map

 

Check for the existence of a key using has:

console.log(myMap.has('name')) // Output: true
Enter fullscreen mode Exit fullscreen mode

 

Removing Key-Value Pairs

 

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

myMap.delete('name')
Enter fullscreen mode Exit fullscreen mode

Or clear the entire Map with the clear method:

myMap.clear()
Enter fullscreen mode Exit fullscreen mode

 

Iterating Over a Map

 

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

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)
}
Enter fullscreen mode Exit fullscreen mode

We can also use the forEach method:

myMap.forEach((value, key) => {
  console.log(key, value);
})
Enter fullscreen mode Exit fullscreen mode

 

Set vs. Array: When to Use Which?

 

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.

 

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.

 

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.

 

Map vs. Object: When to Use Which?

 

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.

 

Key Flexibility

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

 

Iteration Order

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

 

Size Determination

 

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.

 

Performance

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

 

Wrapping Up

 

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.

 

rich-text-editor-for-react npm package

Demo | Documentation

Top comments (4)

Collapse
 
patric12 profile image
Patric

Had no idea about Set and Map! Thanks.

Collapse
 
rasaf_ibrahim profile image
Rasaf Ibrahim

Thanks for your feedback. 🎉

Collapse
 
jerrymarvis profile image
Ogundele babatunde Jeremiah

Great job, thank you for this wonderful post.

Collapse
 
rasaf_ibrahim profile image
Rasaf Ibrahim

Thanks for your feedback. 🎉