Tuesday, June 24, 2025

Javascript Module 16

  Module 16 : Javascript Maps and Sets 

🧠 Concept Overview

πŸ”Ή What is a Map?








A Map is a collection of key-value pairs where:

Keys can be of any type (not just strings or symbols like in objects).

Maintains the insertion order of keys.

js

code

const myMap = new Map(); myMap.set('name', 'Alice'); myMap.set(100, 'number key'); myMap.set(true, 'boolean key');

πŸ”Ή What is a Set?

A Set is a collection of unique values.

Automatically removes duplicates.

Maintains the insertion order of values.

js

 code

const mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(2); // Duplicate - will not be added


πŸ” Difference Between Object, Array, Map, and Set

Feature

Object

Array

Map

Set

Key type

Strings/Symbols

Indexes

Any type

N/A (only values)

Order

Not guaranteed

Indexed order

Insertion order

Insertion order

Iteration

for...in

for, forEach

forEach, iterator

forEach, iterator

Duplicate keys

Not allowed

Allowed

Not allowed

Not allowed



πŸ› ️ Practical Methods

🧭 Map Methods

Method

Description

Example

set(key, value)

Adds or updates a key-value pair

map.set('a', 1);

get(key)

Retrieves value for a key

map.get('a'); // 1

has(key)

Checks if key exists

map.has('a'); // true

delete(key)

Removes a key-value pair

map.delete('a');

clear()

Removes all entries

map.clear();

size

Returns the number of pairs

map.size;


πŸ” Map Iteration

js

 code

const userMap = new Map([ ['name', 'John'], ['age', 30] ]); for (let [key, value] of userMap) { console.log(`${key}: ${value}`); }


🧭 Set Methods








Method

Description

Example

add(value)

Adds a unique value

set.add(1);

has(value)

Checks if a value exists

set.has(1);

delete(value)

Removes a value

set.delete(1);

clear()

Removes all values

set.clear();

size

Returns the number of elements

set.size;


πŸ” Set Iteration

js

code

const fruits = new Set(['apple', 'banana', 'apple']); for (let fruit of fruits) { console.log(fruit); }


πŸ§ͺ Practical Examples

πŸ” Example 1: Frequency Counter using Map

js

code

function countWords(str) { const words = str.split(' '); const wordMap = new Map(); for (let word of words) { word = word.toLowerCase(); wordMap.set(word, (wordMap.get(word) || 0) + 1); } return wordMap; } console.log(countWords('apple banana apple orange'));

πŸ” Example 2: Removing Duplicates using Set

js

 code

function removeDuplicates(arr) { return [...new Set(arr)]; } console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));

πŸ” Example 3: Caching with Map



js

 code

const cache = new Map(); function expensiveCalculation(x) { if (cache.has(x)) return cache.get(x); let result = x * x; // Simulate expensive operation cache.set(x, result); return result; } console.log(expensiveCalculation(4)); // Calculates console.log(expensiveCalculation(4)); // Returns cached


πŸ’‘Research Understanding

1. Performance

Map performs better than objects for frequent additions/removals.

Set is more efficient for checking existence of values than arrays using .includes().

2. Memory Usage

Map and Set have optimized internal representations, especially for large collections.

3. Use Cases


Use Case

Preferred Data Structure

Caching

Map

Lookup Table

Map

Unique list of tags

Set

Duplicate removal

Set

Grouping data

Map



πŸŽ“ Guidance












Introduce Maps and Sets conceptually.

Compare with Arrays and Objects.

πŸ§ͺ Hands-On Demonstration 

( examples (e.g., counting, duplicate removal).

Live code

🧠 Practice Exercises Exercise 1: Create a map of countries and their capitals.

js

code

const countryMap = new Map(); // Add at least 5 countries with their capitals.

Exercise 2: Remove duplicates from a list of names using Set.

Exercise 3: Write a function that tracks how many times each character appears in a string using Map.


🧩 Assignments

Build a Voting App

Use a Map to track votes for candidates and display a leaderboard.

Set Intersection Function

Write a function that returns the common elements between two arrays using Set.


πŸ“š Summary











Feature

Map

Set

Stores key-value

Unique values

Maintains insertion order

Iterable

Keys/values of any type


πŸ“Œ Conclusion

Understanding Map and Set is crucial for writing modern, efficient JavaScript code. They solve  problems more elegantly than Object and Array in certain contexts. With proper usage, they lead to better performance, cleaner code, and fewer bugs.


No comments:

Post a Comment

Javascript Module 16

  Javascript Module 16  If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test ...