🧬 JavaScript Advanced Data Types
Estimated reading: 5 minutes 11 views

JavaScript Set & Map Methods: A Comprehensive Guide

In JavaScript, both Set and Map are part of the ES6 (ECMAScript 2015) features, providing efficient ways to manage collections of unique values and key-value pairs, respectively. Understanding the various methods associated with Set and Map can significantly enhance the efficiency of your code when dealing with data structures.

In this article, we’ll explore:

  • Set and Map definitions and use cases
  • Detailed explanation of methods available for Set and Map
  • Real-world examples showcasing practical implementations
  • Key differences between Set and Map

📌 What is a Set in JavaScript?

A Set is a collection of unique values, meaning no duplicate values are allowed. It is particularly useful when you need to store data where duplicates are unnecessary and you need fast lookup and removal of items.

💡 Key Characteristics of a Set:

  • Unique values: No duplicates allowed.
  • Insertion order: Elements maintain their insertion order.
  • Efficient lookup: Adds and checks for values faster than arrays.

🧩 Set Methods

JavaScript provides a variety of methods to manipulate sets. Let’s look at the commonly used ones:

1. add(value)

Adds a new element with the specified value to the Set. If the value already exists, the Set will not add it.

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2);  // Duplicate, will not be added
console.log(mySet); // Output: Set { 1, 2 }

Explanation: add() adds values to the Set. Duplicates are ignored.

2. delete(value)

Removes the specified value from the Set. Returns true if the value was removed, and false otherwise.

let mySet = new Set([1, 2, 3]);
mySet.delete(2);
console.log(mySet); // Output: Set { 1, 3 }

Explanation: delete() removes the specified element from the Set.

3. has(value) 🔍

Checks whether the Set contains the specified value. Returns true if the value is found, and false otherwise.

let mySet = new Set([1, 2, 3]);
console.log(mySet.has(2)); // Output: true
console.log(mySet.has(4)); // Output: false

Explanation: has() checks if the value exists in the Set.

4. clear() 🧹

Removes all elements from the Set.

let mySet = new Set([1, 2, 3]);
mySet.clear();
console.log(mySet); // Output: Set {}

Explanation: clear() empties the entire Set.

5. size 📏

Returns the number of elements in the Set.

let mySet = new Set([1, 2, 3]);
console.log(mySet.size); // Output: 3

Explanation: size returns the total count of unique elements in the Set.


📌 What is a Map in JavaScript?

A Map is a collection of key-value pairs where both the keys and values can be of any data type. The Map object preserves the order of insertion, making it useful when the order of key-value pairs matters.

💡 Key Characteristics of a Map:

  • Key-value pairs: Stores pairs where keys are unique.
  • Insertion order: Map preserves insertion order.
  • Key types: Both keys and values can be any data type.

🧩 Map Methods

The Map object also has several built-in methods for interacting with key-value pairs. Let’s examine them:

1. set(key, value) 🔑➡️

Adds or updates the value for a specified key. If the key already exists, the value will be updated.

let myMap = new Map();
myMap.set("name", "Alice");
myMap.set("age", 25);
console.log(myMap); // Output: Map { 'name' => 'Alice', 'age' => 25 }

Explanation: set() adds a new key-value pair or updates the existing pair if the key is already in the Map.

2. get(key) 🏷️🔍

Retrieves the value associated with a specified key.

let myMap = new Map([["name", "Alice"], ["age", 25]]);
console.log(myMap.get("name")); // Output: "Alice"

Explanation: get() retrieves the value for the specified key.

3. delete(key) ❌🔑

Removes the specified key-value pair from the Map.

let myMap = new Map([["name", "Alice"], ["age", 25]]);
myMap.delete("age");
console.log(myMap); // Output: Map { 'name' => 'Alice' }

Explanation: delete() removes a key-value pair based on the key.

4. has(key) 🔍🔑

Checks if a specific key exists in the Map. Returns true if the key exists, otherwise false.

let myMap = new Map([["name", "Alice"], ["age", 25]]);
console.log(myMap.has("age")); // Output: true
console.log(myMap.has("address")); // Output: false

Explanation: has() checks if a key exists in the Map.

5. clear() 🧹🔑

Removes all key-value pairs from the Map.

let myMap = new Map([["name", "Alice"], ["age", 25]]);
myMap.clear();
console.log(myMap); // Output: Map {}

Explanation: clear() removes all elements in the Map.

6. size 📏

Returns the number of key-value pairs in the Map.

let myMap = new Map([["name", "Alice"], ["age", 25]]);
console.log(myMap.size); // Output: 2

Explanation: size returns the number of key-value pairs in the Map.


🔍 Key Differences Between Set & Map

FeatureSetMap
Storage TypeCollection of unique valuesCollection of key-value pairs
Data Type of KeysN/A (only values)Any data type (primitive or object)
Insertion OrderYesYes
Duplicate ValuesNot allowedNot allowed
Methods for Interactionadd, delete, has, clear, sizeset, get, delete, has, clear, size

💡 Best Practices for Using Set & Map

  • Set: Ideal for situations where you need to maintain a collection of unique values (e.g., removing duplicates from an array).
  • Map: Use Map when you need a collection of key-value pairs with a guarantee of key uniqueness and insertion order (e.g., storing metadata or configuration settings).

Summary

In this article, we’ve learned about Set and Map in JavaScript, exploring their methods, differences, and practical use cases. Understanding these two data structures can improve your code’s efficiency and readability, especially when working with unique values or key-value pairs.


❓ FAQs

❓ What is the difference between a Set and an Array in JavaScript?

Set stores unique values and provides faster lookups and insertions. Arrays, on the other hand, can contain duplicate values and are more suited for ordered collections. Arrays also have more built-in methods for manipulation and iteration.

❓ Can you use objects as keys in a Map?

Yes, in JavaScript Map objects can have any data type as keys, including objects, which is a feature that Set does not support.

❓ When should I use a Set over an Array?

You should use a Set when you need to store unique values and don’t need to worry about the order of insertion or the need for additional methods (like push in arrays).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — Set & Map Methods

Or Copy Link

CONTENTS
Scroll to Top