DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Working with Maps and Sets in JavaScript: A Comprehensive Guide

Working with Maps and Sets in JavaScript

Maps and Sets are two important data structures introduced in ES6 (ECMAScript 2015) that offer enhanced functionality over traditional objects and arrays. Both Maps and Sets allow you to store unique values and work with data in a more organized and efficient way.

1. Maps in JavaScript

A Map is a collection of key-value pairs where both keys and values can be any data type. Unlike objects, which can only have strings or symbols as keys, Maps allow any value (objects, arrays, functions, etc.) to be used as a key.

Creating a Map

To create a Map, you can use the Map constructor:

const map = new Map();
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can initialize a Map with an array of key-value pairs:

const map = new Map([
  ['name', 'Alice'],
  ['age', 25],
  ['city', 'New York']
]);

console.log(map);
Enter fullscreen mode Exit fullscreen mode

Adding Entries to a Map

You can add entries using the set() method:

const map = new Map();

map.set('name', 'John');
map.set('age', 30);
map.set('city', 'Los Angeles');

console.log(map);
Enter fullscreen mode Exit fullscreen mode

Accessing Values in a Map

You can access the value associated with a key using the get() method:

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

console.log(map.get('name'));  // Output: Alice
console.log(map.get('age'));   // Output: 25
Enter fullscreen mode Exit fullscreen mode

Checking for a Key in a Map

To check if a key exists, use the has() method:

const map = new Map([
  ['name', 'John'],
  ['age', 30]
]);

console.log(map.has('name'));  // Output: true
console.log(map.has('city'));  // Output: false
Enter fullscreen mode Exit fullscreen mode

Removing Entries from a Map

You can remove a key-value pair using the delete() method:

map.delete('age');
console.log(map.has('age'));  // Output: false
Enter fullscreen mode Exit fullscreen mode

To clear all entries from the Map:

map.clear();
console.log(map.size);  // Output: 0
Enter fullscreen mode Exit fullscreen mode

Iterating Over a Map

You can iterate over the key-value pairs in a Map using forEach(), or for...of loop:

const map = new Map([
  ['name', 'Alice'],
  ['age', 25]
]);

// Using forEach
map.forEach((value, key) => {
  console.log(key, value);
});

// Using for...of
for (const [key, value] of map) {
  console.log(key, value);
}
Enter fullscreen mode Exit fullscreen mode

2. Sets in JavaScript

A Set is a collection of unique values, meaning it automatically removes any duplicate values. Unlike arrays, which can store multiple identical elements, Sets ensure that every value in the collection is unique.

Creating a Set

You can create a Set using the Set constructor:

const set = new Set();
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can initialize a Set with an array of values:

const set = new Set([1, 2, 3, 4, 5]);
console.log(set);
Enter fullscreen mode Exit fullscreen mode

Adding Values to a Set

You can add values to a Set using the add() method:

const set = new Set();

set.add(1);
set.add(2);
set.add(3);
set.add(2);  // Duplicate value, won't be added

console.log(set);  // Output: Set { 1, 2, 3 }
Enter fullscreen mode Exit fullscreen mode

Checking for a Value in a Set

To check if a value exists in a Set, use the has() method:

console.log(set.has(2));  // Output: true
console.log(set.has(4));  // Output: false
Enter fullscreen mode Exit fullscreen mode

Removing Values from a Set

You can remove a value from a Set using the delete() method:

set.delete(2);
console.log(set.has(2));  // Output: false
Enter fullscreen mode Exit fullscreen mode

To clear all values from the Set:

set.clear();
console.log(set.size);  // Output: 0
Enter fullscreen mode Exit fullscreen mode

Iterating Over a Set

You can iterate over the values in a Set using forEach() or for...of loop:

const set = new Set([1, 2, 3, 4]);

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

// Using for...of
for (const value of set) {
  console.log(value);
}
Enter fullscreen mode Exit fullscreen mode

3. Comparison Between Maps and Sets

Feature Map Set
Storage Stores key-value pairs Stores unique values only
Key Types Any type (objects, arrays, primitive types) Only values (no keys)
Uniqueness Keys must be unique, values can repeat Values must be unique
Order of Elements Iterates in insertion order Iterates in insertion order
Size map.size set.size
Methods set(), get(), has(), delete(), clear() add(), has(), delete(), clear()

4. Use Cases for Maps and Sets

  • Maps are useful when you need to associate unique keys with specific values. Examples include:

    • Storing user preferences
    • Storing configuration options
    • Caching data based on keys
  • Sets are ideal when you need to store a collection of unique values. Examples include:

    • Tracking unique visitors on a website
    • Removing duplicate values from an array
    • Keeping track of items that have been processed or seen

Conclusion

  • Maps offer efficient key-value pair storage with support for any data type as keys, and they maintain insertion order.
  • Sets store unique values and are particularly useful when you want to ensure no duplicates in a collection.

Both Maps and Sets provide powerful features and can help you manage data in a more structured and efficient way.


Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Top comments (0)