JS Map & Set

Understanding JavaScript Map and Set

Introduction

JavaScript is a powerful programming language with many built-in features that help manage data efficiently. Among the many data structures available, Maps and Sets are two useful tools for storing and managing data collections. These two structures may seem similar at first, but they have important differences.

In this guide, we will explore both Map and Set in detail, explaining how they work, how they are different, and when to use each.

Differences Between Map and Set

While both Map and Set are used to store data collections, their behavior and purpose are quite different. Let’s compare them directly:

Feature Map Set
Stored Data Key-value pairs (each key maps to a value) Only values (no keys)
Keys Can be any data type (e.g., string, number, object) Not applicable (only values)
Values Can be any data type Can be any data type
Unique Entries Keys are unique, values can be duplicated Only unique values (duplicates are ignored)
Order Keys are ordered by insertion Values are ordered by insertion
Methods .set(), .get(), .has(), .delete(), .clear() .add(), .has(), .delete(), .clear()
Size Property Yes, .size Yes, .size
Use Case Storing key-value pairs where keys can be any data type Storing unique values, eliminating duplicates

1. What is a JavaScript Map?

A Map is like a dictionary or address book. It stores pairs of keys and values, where each key points to a specific value. The key can be anything (like a number, string, or even an object), and the value can also be anything. The important thing is that each key in a Map is unique.

Syntax:

new Map([iterable])

Basic Example of a Map:

A Map stores key-value pairs, where keys can be any type.

// Create a Map
let map = new Map();
// Add key-value pairs
map.set(‘name’, ‘Saad’);
map.set(‘age’, 21);
// Get a value by key
console.log(map.get(‘name’)); // Output: Alice
// Check if a key exists
console.log(map.has(‘age’)); // Output: true

Code Explanation:

1. Creating a Map:

new Map([iterable])

new Map(): This creates a new Map object. A Map is a collection of key-value pairs where both the keys and values can be any type (objects, numbers, strings, etc.).
map is the variable where we store the Map object.

2. Adding Key-Value Pairs:

map.set(‘name’, ‘Saad’);
map.set(‘age’, 21);

map.set(key, value): This method is used to add key-value pairs to the Map.
• map.set(‘name’, ‘Saad’): Adds a key “name” with the value “Saad”.
• map.set(‘age’, 21): Adds a key “age” with the value 21.

After this, the Map looks like this:

Map { ‘name’ => ‘Saad’, ‘age’ => 21 }

3. Getting a Value by Key:

console.log(map.get(‘name’));  // Output: Saad

map.get(key): This method is used to retrieve the value associated with a specific key from the Map.
• map.get(‘name’) returns the value associated with the key “name”, which is “Saad”.
So, the console will log: Saad.

4. Checking if a Key Exists:

console.log(map.has(‘age’));   // Output: true

map.has(key): This method checks if a specific key exists in the Map.
• map.has(‘age’) checks if the key “age” is in the Map. Since we added the key “age” earlier, it returns true.
So, the console will log: true.

Output:
what-is-js-map

Another Example:

<body>
<script>
// Create a new Map
const phonebook = new Map();
// Add key-value pairs using the .set() method
phonebook.set(“Alice”, “123-456-7890”);
phonebook.set(“Bob”, “987-654-3210”);
console.log(phonebook.get(“Alice”)); // Output: 123-456-7890
</script>
</body>

Code Explanation:

1. Creating a New Map

const phonebook = new Map();

new Map(): This creates a new empty Map object called phonebook.
A Map is a collection of key-value pairs. In this case, we will use names (like “Saad” and “Amir”) as keys and their phone numbers as values.

2. Adding Key-Value Pairs to the Map

phonebook.set(“Saad”, “123-456-7890”); phonebook.set(“Amir”, “987-654-3210”);

set(key, value): This method is used to add key-value pairs to a Map.
• The first line adds the key “Saad” with the value “123-456-7890” to the phonebook Map.
• The second line adds the key “Amir” with the value “987-654-3210” to the Map.

After these operations, the phonebook Map looks like this:

{ “Saad” => “123-456-7890”, “Amir” => “987-654-3210” }

3. Retrieving a Value from the Map

console.log(phonebook.get(“Saad”)); // Output: 123-456-7890

get(key): This method is used to retrieve the value associated with the given key from the Map.
In this case, we are retrieving the phone number of “Saad”.
The console.log() prints “123-456-7890” because that is the value associated with the key “Saad” in the phonebook Map.

Output:

2. What is a JavaScript Set?

A Set is like a collection of unique items. It stores only distinct values — no duplicates allowed. A Set automatically removes any repeated values you try to add.

Basic Example of a Map:

A Set stores unique values, no duplicates allowed.

// Create a Set
let set = new Set();
// Add values
set.add(1);
set.add(2);
set.add(2); // Duplicate, won’t be added
// Check if a value exists
console.log(set.has(1)); // Output: true
// Get the size of the Set
console.log(set.size); // Output: 2

Code Explanation:

1. Creating a Set:

let set = new Set();

new Set(): This creates a new Set object. A Set is a collection of unique values, meaning it automatically removes duplicates. Unlike arrays, a Set only stores each value once.
set is the variable where we store the Set object.

2. Adding Values to the Set:

set.add(1);
set.add(2);
set.add(2); // Duplicate, won’t be added

set.add(value): This method adds a value to the Set.
• set.add(1): Adds the value 1 to the Set.
• set.add(2): Adds the value 2 to the Set.
• set.add(2): Duplicate value — since 2 is already in the Set, it won’t be added again.

After this, the Set looks like:

Set { 1, 2 }

The Set automatically ignores duplicate values, so even though we tried to add 2 twice, it only exists once in the Set.

3. Checking if a Value Exists in the Set:

console.log(set.has(1));  // Output: true

set.has(value): This method checks if a specific value is present in the Set.
• set.has(1) checks if the value 1 is in the Set. Since 1 was added, it returns true.
So, the console will log: true.

4. Getting the Size of the Set:

console.log(set.size);    // Output: 2

set.size: This property returns the number of unique values in the Set.
• In our case, the Set contains two unique values: 1 and 2.
So, the console will log: 2.

Output:

<body>
<script>
// Create a new Map
// Create a new Set
const fruits = new Set();
// Add values to the Set using .add()
fruits.add(“apple”);
fruits.add(“banana”);
fruits.add(“apple”); // Duplicate value, will not be added
console.log(fruits); // Output: Set { ‘apple’, ‘banana’ }
</script>
</body>

const fruits = new Set();

new Set(): This creates a new empty Set object called fruits.
A Set is a collection of unique values. Unlike an array, it does not allow duplicate values. If you try to add a duplicate, it will simply be ignored.

2. Adding Values to the Set

fruits.add(“apple”); fruits.add(“banana”); fruits.add(“apple”); // Duplicate value, will not be added

add(value): This method is used to add a value to a Set.
• The first line adds the value “apple” to the fruits Set.
• The second line adds the value “banana” to the Set.
• The third line attempts to add “apple” again. Since Sets automatically eliminate duplicate values, the second “apple” is not added.

After these operations, the fruits Set looks like this:

Set { ‘apple’, ‘banana’ }

Even though “apple” was added twice, it appears only once because Sets store only unique values.

3. Displaying the Set

Set { ‘apple’, ‘banana’ }

console.log(fruits): This prints the fruits Set to the console.
The output is Set { ‘apple’, ‘banana’ }, showing that the Set contains only two unique values: “apple” and “banana”.

Output:
what-is-js-set-2

Course Video

YouTube Reference :

Examples for Practice

1. Write a JS program to Map an Element using Map Object in JS. For Example, create a Map Object Name called Fruits and Map the Different Name of Fruits with Different Values.

The task is to write a JavaScript program that uses a Map object to map different names of fruits to their respective values.
1. Create a Map Object:
Use the Map object in JavaScript to create a map of fruits.
2. Map Fruits to Values:
Add entries to the Map where the keys are different names of fruits, and the values are associated values or any related information.

Here’s an example program:

// Step 1: Create a Map Object
const fruitsMap = new Map();

// Step 2: Map Fruits to Values
fruitsMap.set(“Apple”, “Red and sweet”);
fruitsMap.set(“Banana”, “Yellow and curved”);
fruitsMap.set(“Orange”, “Orange and citrusy”);
fruitsMap.set(“Grapes”, “Small and juicy”);

// Display the mapped values
console.log(“Fruits and their descriptions:”);

// Iterate through the Map entries
for (const [fruit, description] of fruitsMap) {
console.log(`${fruit}: ${description}`);
}

Output

2. Given an array of numbers, create a Set called uniqueNumbers to store unique numbers.

The task is to to create a JavaScript program that takes an array of numbers and uses a Set to store unique numbers.
1. Create a Set:
Use the Set object in JavaScript to create a set called uniqueNumbers.
2. Add Numbers to the Set:
Iterate through the array of numbers and add each number to the set. The Set automatically ensures that unique values are stored.

Here’s an example program:

// Step 1: Create a Set called uniqueNumbers
const uniqueNumbers = new Set();

// Step 2: Add Numbers to the Set
const numbersArray = [5, 10, 15, 10, 20, 5, 25, 30, 15];

// Iterate through the array and add each number to the set
numbersArray.forEach(number => {
uniqueNumbers.add(number);
});

// Display the unique numbers
console.log(“Unique numbers in the array:”);
console.log(Array.from(uniqueNumbers));

Output

3. Write a JS program to Set a Map Object Using a Set Object in JS. For Example, create a Map Object Name called Vegetables and Add the Different Name of Fruits as a Key with Different Values using the set Object Method and also Proint the value Of different values of the Key using the Get object.

The task is to write a JavaScript program that uses a Set object to set values in a Map object.
1. Create a Set and a Map:
– Use the Set object to store unique values.
– Use the Map object to create a mapping of vegetables.
2. Add Values to the Set and Map:
– Use the Set object to store unique values (in this case, different values associated with a specific vegetable).
– Use the Map object to associate a vegetable name with the Set of values.
3. Print Values of Different Keys:
Use the get method of the Map object to retrieve the Set of values associated with a specific vegetable name.

Here’s an example program:

// Step 1: Create a Set and a Map
const uniqueValuesSet = new Set();
const vegetablesMap = new Map();

// Step 2: Add Values to the Set and Map
// Add values to the set for a specific vegetable
uniqueValuesSet.add(“Green”);
uniqueValuesSet.add(“Nutritious”);

// Set the Map object with the vegetable name as the key and the set of values as the value
vegetablesMap.set(“Broccoli”, uniqueValuesSet);

// Step 3: Print Values of Different Keys
// Use the get method to retrieve the Set of values for a specific vegetable
const broccoliValues = vegetablesMap.get(“Broccoli”);

// Display the values associated with the vegetable
console.log(“Values associated with Broccoli:”);
console.log(Array.from(broccoliValues));

Output

4. Create a Map called fruitPrices with keys as fruit names and values as their respective prices. Add entries for “apple”, “banana”, and “orange”.

The task is to create a JavaScript program that uses a Map object to store prices for different fruits.
1. Create a Map Object:
Use the Map object in JavaScript to create a map called fruitPrices.
2. Add Entries to the Map:
Use the set method of the Map object to add entries, where the keys are different fruit names, and the values are their respective prices.

Here’s an example program:

// Step 1: Create a Map Object called fruitPrices
const fruitPrices = new Map();

// Step 2: Add Entries to the Map
fruitPrices.set(“apple”, 1.5); // Price for an apple
fruitPrices.set(“banana”, 0.8); // Price for a banana
fruitPrices.set(“orange”, 1.2); // Price for an orange

// Display the fruit prices
console.log(“Fruit Prices:”);

// Iterate through the Map entries
for (const [fruit, price] of fruitPrices) {
console.log(`${fruit}: $${price.toFixed(2)}`);
}

Output

5. Given two arrays, one with student names and the other with their corresponding grades, create a Map called studentScores to store each student’s name and grade.

The task is to create a JavaScript program that uses a Map object to store student names and their corresponding grades.
1. Create Two Arrays:
Have two arrays, one for student names and the other for their corresponding grades.
2. Create a Map Object:
Use the Map object in JavaScript to create a map called studentScores.
3. Add Entries to the Map:
Use the set method of the Map object to add entries, where the keys are student names, and the values are their corresponding grades.

Here’s an example program:

// Step 1: Create Arrays for Student Names and Grades
const studentNames = [“Alice”, “Bob”, “Charlie”, “David”];
const studentGrades = [85, 92, 78, 95];

// Step 2: Create a Map Object called studentScores
const studentScores = new Map();

// Step 3: Add Entries to the Map
for (let i = 0; i < studentNames.length; i++) {
studentScores.set(studentNames[i], studentGrades[i]);
}

// Display the student scores
console.log(“Student Scores:”);

// Iterate through the Map entries
for (const [student, grade] of studentScores) {
console.log(`${student}: ${grade}`);
}

Output

Frequently Asked Questions

Still have a question?

Let's talk

A Map object stores key-value pairs and allows keys of any data type, offering more flexibility than regular objects. Learn more in our JavaScript map set free course video.

Use the new Map() constructor and the set() method to add key-value pairs.
Example:

let myMap = new Map(); 

myMap.set(‘key1’, ‘value1’); 

myMap.set(2, ‘value2’); 

Explore this in the JS map and set with free video tutorial.

A Set stores unique values, whereas a Map stores key-value pairs. Discover their differences in the Free JavaScript map set tutorial for beginners.

  • For Map: Use the has() method with a key.
  • For Set: Use the has() method with a value.
    Example:

myMap.has(‘key1’); // true 

mySet.has(‘value1’); // true 

Find this explained in the JavaScript map and set with free tutorial.

Yes, both Map and Set are iterable. Use for…of or methods like keys(), values(), or entries().
Example:

for (let [key, value] of myMap) { 

  console.log(key, value); 

Learn these techniques in the JavaScript map set free course video.

Use the delete() method.
Example:

myMap.delete(‘key1’); 

mySet.delete(‘value1’); 

Check out practical examples in the JS map and set with free video tutorial.

  • WeakMap: Only allows objects as keys, and references are weak (subject to garbage collection).
  • Map: Supports keys of any data type and maintains strong references.
    Explore their differences in the Free JavaScript map set tutorial for beginners.

 

Use the Set constructor.
Example:

let uniqueSet = new Set([1, 2, 2, 3]); 

console.log([…uniqueSet]); // [1, 2, 3] 

Learn this technique in the JavaScript map and set with free tutorial.

  • Use Map when you need key-value pairs with non-string keys.
  • Use Set for storing unique values without duplicates.
    Find helpful insights in the JavaScript map set free course video.
  • Map: set(), get(), has(), delete(), clear(), size.
  • Set: add(), has(), delete(), clear(), size.
    Explore these methods in the JS map and set with free video tutorial.