Modern JavaScript, Map and Set Practice Questions with Solutions

Introductions

Modern JavaScript provides several useful features for handling data more efficiently. Map and Set are especially useful when working with unique values, key-value data, and collections.

In this chapter, you will practice Map, Set, WeakMap, WeakSet, optional chaining, nullish coalescing, and other important modern JavaScript features with simple, practical examples. Modern JavaScript, Map and Set practice questions with solutions help to build concepts.

Question 1: Create a Basic Map

Problem

Create a Map that stores a student’s name, age, and course. Display all three values.

Solution

const student = new Map();

student.set("name", "Rahul");
student.set("age", 20);
student.set("course", "JavaScript");

console.log(student.get("name"));
console.log(student.get("age"));
console.log(student.get("course"));

Output

Rahul
20
JavaScript

Step-by-step Explanation

A Map stores data in key-value pairs.

Create a Map:

const student = new Map();

Add values using set():

student.set("name", "Rahul");

Retrieve a value using get():

student.get("name");

A Map can contain different types of keys and values.


Question 2: Check Whether a Map Contains a Key

Problem

Create a Map containing product information. Check whether a "price" key exists.

Solution

const product = new Map();

product.set("name", "Keyboard");
product.set("price", 1200);

console.log(product.has("price"));
console.log(product.has("stock"));

Output

true
false

Step-by-step Explanation

The has() method checks whether a key exists:

product.has("price");

If the key exists, it returns:

true

If it does not exist:

false

Question 3: Loop Through a Map

Problem

Create a Map containing three students and their marks. Display each student’s name and marks.

Solution

const marks = new Map();

marks.set("Rahul", 85);
marks.set("Aman", 90);
marks.set("Priya", 88);

marks.forEach(function(mark, student) {
    console.log(student + ": " + mark);
});

Output

Rahul: 85
Aman: 90
Priya: 88

Step-by-step Explanation

forEach() can be used to loop through a Map.

The callback receives:

value, key

So:

function(mark, student)

means:

  • mark → value
  • student → key

You can also use for...of:

for (const [student, mark] of marks) {
    console.log(student + ": " + mark);
}

Question 4: Create a Set with Unique Values

Problem

Create a Set containing several numbers, including duplicate values. Display the Set.

Solution

const numbers = new Set([
    10,
    20,
    20,
    30,
    30,
    40
]);

console.log(numbers);

Output

Set(4) { 10, 20, 30, 40 }

Step-by-step Explanation

A Set stores unique values.

The duplicate values:

20
20
30
30

are automatically removed.

The final Set contains:

10
20
30
40

This makes Set useful when duplicate values should be removed.


Question 5: Remove Duplicate Values from an Array

Problem

Remove duplicate numbers from an array using Set.

Solution

const numbers = [
    10,
    20,
    20,
    30,
    40,
    40,
    50
];

const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);

Output

[10, 20, 30, 40, 50]

Step-by-step Explanation

First, convert the array into a Set:

new Set(numbers);

The Set automatically removes duplicates.

Then use the spread operator:

[...new Set(numbers)]

to convert the Set back into an array.

This is one of the most useful practical applications of Set.


Question 6: Use Map with Object Keys

Problem

Create two objects representing students and use the objects as keys in a Map.

Solution

const student1 = {
    name: "Rahul"
};

const student2 = {
    name: "Priya"
};

const scores = new Map();

scores.set(student1, 90);
scores.set(student2, 95);

console.log(scores.get(student1));
console.log(scores.get(student2));

Output

90
95

Step-by-step Explanation

Unlike normal objects, a Map can use objects as keys.

Here:

scores.set(student1, 90);

means:

student1 → 90

And:

scores.set(student2, 95);

means:

student2 → 95

This is useful when you want to associate data directly with object references.


Question 7: Use Optional Chaining

Problem

Create a user object where address may not exist. Safely try to access the user’s city.

Solution

const user = {
    name: "Aman"
};

console.log(user.address?.city);

Output

undefined

Step-by-step Explanation

Normally, this could cause an error:

user.address.city;

because address does not exist.

Optional chaining:

user.address?.city;

checks whether address exists before trying to access city.

If address is missing, JavaScript returns:

undefined

instead of throwing an error.


Question 8: Use Nullish Coalescing

Problem

Display "Guest" when a username is null or undefined.

Solution

const username = null;

const displayName = username ?? "Guest";

console.log(displayName);

Output

Guest

Step-by-step Explanation

The ?? operator is called the nullish coalescing operator.

username ?? "Guest"

means:

Use username if it is not null or undefined; otherwise use "Guest".

For example:

const username = "Rahul";

console.log(username ?? "Guest");

Output:

Rahul

An important difference from || is that ?? does not replace other falsy values such as 0, false, or an empty string.


Question 9: Use WeakMap

Problem

Create a WeakMap to store private-looking metadata associated with a user object.

Solution

const user = {
    name: "Rahul"
};

const userData = new WeakMap();

userData.set(user, {
    loginCount: 5
});

console.log(userData.get(user));

Output

{ loginCount: 5 }

Step-by-step Explanation

A WeakMap stores key-value pairs where the keys must be objects.

Here:

userData.set(user, {
    loginCount: 5
});

associates extra data with the user object.

The data can be retrieved using:

userData.get(user);

One important characteristic is that WeakMap does not prevent its object keys from being garbage-collected when there are no other references to those objects.


Question 10: Build a Practical Product Collection

Problem

Create a product collection using Map, remove duplicate categories using Set, and safely display an optional discount using modern JavaScript.

Solution

const products = new Map();

products.set(1, {
    name: "Keyboard",
    category: "Electronics",
    discount: 10
});

products.set(2, {
    name: "Notebook",
    category: "Stationery"
});

products.set(3, {
    name: "Mouse",
    category: "Electronics",
    discount: 5
});

const categories = new Set();

products.forEach(function(product) {
    categories.add(product.category);
});

console.log("Categories:");

for (const category of categories) {
    console.log(category);
}

console.log("Product Discounts:");

products.forEach(function(product) {

    const discount = product.discount ?? 0;

    console.log(
        product.name + ": " + discount + "%"
    );

});

Output

Categories:
Electronics
Stationery

Product Discounts:
Keyboard: 10%
Notebook: 0%
Mouse: 5%

Step-by-step Explanation

First, products are stored in a Map:

const products = new Map();

Each product gets a unique key:

products.set(1, {...});

Next, a Set stores categories:

const categories = new Set();

Because Set only stores unique values, "Electronics" appears only once even though two products belong to that category.

The discount is safely handled using:

const discount = product.discount ?? 0;

The Notebook does not have a discount property, so 0 is used.

This example combines:

Map
+
Set
+
forEach()
+
nullish coalescing
+
objects

Key Takeaways

  • Map stores key-value pairs.
  • Map keys can be strings, numbers, objects, functions, and other values.
  • set() adds or updates a Map entry.
  • get() retrieves a Map value.
  • has() checks whether a Map key exists.
  • delete() removes a Map entry.
  • clear() removes all Map entries.
  • Set stores unique values.
  • Set automatically removes duplicate values.
  • add() adds a value to a Set.
  • has() checks whether a Set contains a value.
  • delete() removes a Set value.
  • WeakMap stores object-keyed data without keeping those keys alive solely because of the WeakMap.
  • WeakSet stores objects weakly and only accepts objects as members.
  • Optional chaining ?. safely accesses potentially missing properties.
  • Nullish coalescing ?? provides a fallback only for null or undefined.
  • Map is useful when you need flexible key-value relationships.
  • Set is useful for unique collections and duplicate removal.

FAQs

1. What is a Map in JavaScript?

A Map is a collection of key-value pairs.

const users = new Map();

users.set("name", "Rahul");

console.log(users.get("name"));

Output:

Rahul

Unlike a normal object, a Map can use many different data types as keys.

2. What is a Set in JavaScript?

A Set is a collection that stores unique values.

const numbers = new Set([
    10,
    20,
    20,
    30
]);

console.log(numbers);

The duplicate 20 is automatically removed.

3. What is the difference between Map and Set?

The main difference is the type of data they are designed to store.

FeatureMapSet
Stores key-value pairsYesNo
Stores unique valuesKeys are uniqueYes
set()YesNo
add()NoYes
get()YesNo
has()YesYes
delete()YesYes

4. How do you remove duplicate values from an array?

A simple modern approach is:

const numbers = [1, 2, 2, 3, 3, 4];

const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);

Output:

[1, 2, 3, 4]

5. What is optional chaining in JavaScript?

Optional chaining uses ?. to safely access a property or method when part of a chain may be null or undefined.

const user = {};

console.log(user.address?.city);

Output:

undefined

Without optional chaining, trying to access user.address.city in this example would throw an error.

6. What is the ?? operator in JavaScript?

?? is the nullish coalescing operator.

const name = null;

console.log(name ?? "Guest");

Output:

Guest

It uses the right-hand value when the left-hand value is null or undefined.

7. What is the difference between ?? and ||?

They behave differently with falsy values.

const value = 0;

console.log(value || 100);
console.log(value ?? 100);

Output:

100
0

|| treats 0 as falsy, while ?? only falls back for null or undefined.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top