3.3 Data Structures in JavaScript: Set and Map

The `Set` and `Map` data structures in JavaScript offer powerful alternatives to traditional arrays and objects for managing collections of data.

Medium - Hard
Working with Data
Data Structures in JavaScript: Set and Map

Understanding and utilizing the right data structures can significantly enhance the efficiency and readability of your code. Among the various data structures that JavaScript offers, Set and Map stand out for their unique properties and use cases. These structures bring additional power and flexibility to the language, allowing developers to manage collections of data more effectively. Here we are going to explore the Set and Map data structures in JavaScript, highlighting their features, differences, and practical applications.

Understanding the Set

A Set in JavaScript is a collection of unique values. Unlike arrays, where you can have multiple occurrences of the same element, a Set ensures that each element is unique. This characteristic makes Set particularly useful for scenarios where you need to avoid duplicate values and ensure the uniqueness of elements in a collection.

Creating and Modifying a Set

const mySet = new Set();

// Adding values
mySet.add(1);
mySet.add(2);
mySet.add(2); // This will not be added as 2 is already present

console.log(mySet); // Output: Set(2) {1, 2}

// Checking the presence of a value
console.log(mySet.has(1)); // Output: true
console.log(mySet.has(3)); // Output: false

// Removing a value
mySet.delete(1);

// Clearing the set
mySet.clear();

Iterating Over a Set

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

for (const item of mySet) {
  console.log(item);
}

// Output:
// 1
// 2
// 3

Understanding the Map

A Map in JavaScript is a collection of key-value pairs where each key is unique. Maps are similar to objects in that both allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. However, the Map data structure has some significant advantages over objects, particularly the ability to use any value (including objects) as keys and to remember the original insertion order of the keys.

Creating and Modifying a Map

const myMap = new Map();

// Setting key-value pairs
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');

console.log(myMap); // Output: Map(2) {"key1" => "value1", "key2" => "value2"}

// Getting a value by key
console.log(myMap.get('key1')); // Output: "value1"

// Checking the presence of a key
console.log(myMap.has('key2')); // Output: true
console.log(myMap.has('key3')); // Output: false

// Removing a key-value pair
myMap.delete('key1');

// Clearing the map
myMap.clear();

Iterating Over a Map

const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
]);

// Iterating over key-value pairs
for (const [key, value] of myMap) {
  console.log(`${key}: ${value}`);
}

// Output:
// key1: value1
// key2: value2

Set vs. Map: When to Use Which?

  • Use a Set when you need to store a collection of unique values without any particular order.
  • Use a Map when you need to store key-value pairs and there could be a necessity to search, remove, or iterate over items based on keys.

Practical Applications

  • Set: Managing a list of unique items, such as user IDs or book ISBNs.
  • Map: Caching results from a database query where the key could be the query string, and the value is the result set.

By understanding their unique characteristics and appropriate use cases, developers can write more efficient and cleaner code. Whether it's ensuring the uniqueness of elements with Set or maintaining an ordered collection of key-value pairs with Map, these data structures are invaluable tools in the JavaScript developer's arsenal.

Support us ❤️

Buy Us A Coffee