Lecture Notes Of Day 20: JavaScript Set and Map

Rashmi Mishra
0

 

Lecture Notes Of Day 20: 

JavaScript Set and Map

Objective:
The objective of this lesson is to introduce students to two important built-in objects in JavaScript: Set and Map. These objects are designed to store collections of data and allow for efficient storage and retrieval.


1. Introduction to Sets

A Set is a collection of unique values in JavaScript. It is similar to an array but with the following key differences:

  • No duplicate values: A Set can only store unique values, meaning no duplicates are allowed.
  • Order of insertion: The Set maintains the order of the elements, i.e., the first element added is the first element retrieved.
  • Faster lookups: Sets are optimized for storing unique values, so checking if a value is in a Set is faster compared to an array.

Creating a Set

You can create a Set using the Set constructor.

let mySet = new Set();

You can also initialize a Set with an array of values:

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

Adding Items to a Set

To add values to a Set, you can use the add() method.

mySet.add(5);    // Adds the value 5 to the set

mySet.add(10);   // Adds the value 10 to the set

Removing Items from a Set

To remove items from a Set, use the delete() method.

mySet.delete(5);  // Removes the value 5 from the set

Checking for Existence of an Item

To check whether an item exists in the Set, you can use the has() method.

console.log(mySet.has(10));  // true

console.log(mySet.has(5));   // false

Clearing a Set

To remove all elements from a Set, you can use the clear() method.

mySet.clear();

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


2. Introduction to Maps

A Map is a collection of key-value pairs in JavaScript. Unlike objects, where the keys are strings or symbols, in Maps, the keys can be of any data type (including objects, arrays, and even functions). A Map preserves the order of elements and allows for quick retrieval of values by their keys.

Creating a Map

You can create a Map using the Map constructor.

let myMap = new Map();

You can also initialize a Map with an array of key-value pairs:

let myMap = new Map([

  ['name', 'John'],

  ['age', 30],

  ['city', 'New York']

]);

Adding Items to a Map

To add key-value pairs to a Map, use the set() method.

myMap.set('email', 'john@example.com');  // Adds a key-value pair to the map

Accessing Items in a Map

To access the value of a particular key, use the get() method.

console.log(myMap.get('name'));  // Output: John

Removing Items from a Map

To remove a key-value pair from a Map, use the delete() method.

myMap.delete('age');  // Removes the key 'age' and its corresponding value

Checking for Existence of a Key

To check if a Map contains a particular key, use the has() method.

console.log(myMap.has('city'));  // true

console.log(myMap.has('age'));   // false

Clearing a Map

To remove all key-value pairs from a Map, use the clear() method.

myMap.clear();

console.log(myMap);  // Output: Map {}


3. Iterating Over Sets and Maps

Both Sets and Maps can be iterated over, but the methods to do so are different. Let's go over each one:

Iterating Over a Set

You can iterate over a Set using the forEach() method, or you can use a for...of loop.

Using forEach() Method

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

mySet.forEach(value => {

  console.log(value);  // Output: 1, 2, 3, 4

});

Using for...of Loop

for (let value of mySet) {

  console.log(value);  // Output: 1, 2, 3, 4

}

Iterating Over a Map

You can iterate over a Map using the forEach() method, or you can use a for...of loop along with Map's entries(), keys(), or values() methods.

Using forEach() Method

let myMap = new Map([

  ['name', 'John'],

  ['age', 30],

  ['city', 'New York']

]);

 

myMap.forEach((value, key) => {

  console.log(key + ': ' + value); 

  // Output: name: John, age: 30, city: New York

});

Using for...of Loop

You can also use for...of to iterate over keys, values, or entries in a Map.

  • Iterating over entries: (key-value pairs)


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

  console.log(key + ': ' + value); 

  // Output: name: John, age: 30, city: New York

}

  • Iterating over keys:


for (let key of myMap.keys()) {

  console.log(key); 

  // Output: name, age, city

}

  • Iterating over values:

for (let value of myMap.values()) {

  console.log(value); 

  // Output: John, 30, New York

}


4. Summary of Key Differences Between Set and Map

Feature

Set

Map

Data Structure

Stores only unique values.

Stores key-value pairs.

Key Types

Does not have keys.

Keys can be of any data type (objects, arrays, etc.).

Order

Preserves insertion order.

Preserves insertion order.

Duplicates

Does not allow duplicate values.

Allows duplicate values with different keys.

Access

Only stores values, no keys.

Allows access to both keys and values.


5. Use Cases

  • Set: Useful when you need to store unique values and check if an item exists in the collection efficiently. For example, to store a list of unique user IDs or tags.
  • Map: Useful when you need to associate keys with values and perform fast lookups. For example, storing user profiles where the user ID is the key and the profile data is the value.

6. Exercises

1.  Exercise 1: Create a Set, add five numbers to it, and print the Set. Remove one number and print the Set again.

2.  Exercise 2: Create a Map that holds a user's name, age, and email. Retrieve and print the user's name and email.

3.  Exercise 3: Write a function that takes a Map of student names and their scores, and returns the highest score.

4.  Exercise 4: Create a Set from an array, then use forEach() to print each element of the Set.


Conclusion:

In this lesson, we've covered the concepts of Set and Map in JavaScript. Both are powerful tools for storing collections of data. Sets are ideal for storing unique values, while Maps are perfect for associating keys with values. Understanding how to use them effectively can make your code more efficient and easier to manage.

Post a Comment

0Comments

Post a Comment (0)