Back to Web Development
2025-12-247 min read

Keyed collections (Web Development)

Learn Keyed collections (Web Development) step by step with clear examples and exercises.

Title: Keyed Collections (Web Development) - Mastering Maps and Sets

Why This Matters

Keyed collections are essential for modern web development, allowing you to store data in a more organized and flexible manner than traditional arrays. They are particularly useful when dealing with complex data structures, such as objects with multiple properties or collections that require unique identifiers. Understanding keyed collections will help you write cleaner, more efficient code and solve real-world programming challenges.

Keyed collections in web development primarily consist of two main types: Maps and Sets. Both are iterable, meaning you can loop through their elements, but they differ in how they store and access data.

Prerequisites

Before diving into keyed collections, it is essential to have a solid understanding of the following concepts:

  1. HTML and CSS basics
  2. JavaScript fundamentals (variables, functions, loops, etc.)
  3. Understanding of data structures like arrays and objects
  4. Familiarity with DOM manipulation using JavaScript
  5. Knowledge of ES6 features such as arrow functions, template literals, and destructuring assignments
  6. Comfortable working with browser developer tools (inspecting HTML elements, modifying CSS styles, and debugging JavaScript code)

Core Concept

Map

A Map is a key-value pair collection where each unique key corresponds to a value. It allows you to store data in an organized manner and easily retrieve values based on their keys. Here's a simple example of creating a Map and adding key-value pairs:

const myMap = new Map();
myMap.set("name", "John Doe");
myMap.set("age", 30);
myMap.set("job", "Web Developer");

You can access values using the get() method and check if a key exists with the has() method:

console.log(myMap.get("name")); // Outputs "John Doe"
console.log(myMap.has("age")); // Returns true

Map Methods and Properties

  • size: Returns the number of key-value pairs in the Map.
  • clear(): Removes all key-value pairs from the Map.
  • delete(key): Deletes a specific key-value pair from the Map, if it exists.
  • forEach((value, key, map) => {}): Iterates through each key-value pair in the Map and executes the provided callback function for each one.
  • entries(): Returns an iterator that yields all key-value pairs as arrays ([key, value]).
  • keys(): Returns an iterator that yields only the keys of the Map.
  • values(): Returns an iterator that yields only the values of the Map.

Set

A Set is a collection of unique values, where each value can only appear once. It's useful for storing collections of distinct items and performing operations like checking membership or finding intersections with other sets. Here's an example of creating a Set and adding elements:

const mySet = new Set(["apple", "banana", "orange", "grape"]);

You can check if an element is a member of the Set using the has() method:

console.log(mySet.has("apple")); // Returns true

Set Methods and Properties

  • size: Returns the number of elements in the Set.
  • clear(): Removes all elements from the Set.
  • delete(value): Deletes a specific value from the Set, if it exists.
  • add(value): Adds a new value to the Set.
  • forEach((value, set) => {}): Iterates through each element in the Set and executes the provided callback function for each one.

Worked Example

Let's create a simple web application that allows users to add their names and ages to a Map, then displays the collected data in an HTML table using JavaScript and DOM manipulation.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Keyed Collections Example</title>
</head>
<body>
<h1>Keyed Collections Example</h1>
<table id="dataTable"></table>
<form id="addDataForm">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required>
<label for="age">Age:</label>
<input type="number" name="age" id="age" required>
<button type="submit">Add Data</button>
</form>
<script>
const data = new Map();
const table = document.getElementById("dataTable");
const form = document.getElementById("addDataForm");

form.addEventListener("submit", function(event) {
event.preventDefault();
addData(event.target.name.value, event.target.age.value);
updateTable();
});

function addData(name, age) {
data.set(name, age);
}

function updateTable() {
table.innerHTML = "";
for (const [key, value] of data.entries()) {
const row = table.insertRow(-1);
const nameCell = row.insertCell(0);
const ageCell = row.insertCell(1);
nameCell.textContent = key;
ageCell.textContent = value;
}
}
</script>
</body>
</html>

Common Mistakes

  1. Forgetting to initialize a Map or Set before adding elements.
  2. Trying to access a value in a Map using the wrong key.
  3. Adding duplicate values to a Set.
  4. Using for loops instead of for...of loops when iterating over Maps and Sets, which can lead to unexpected results.
  5. Not properly handling cases where a key or value is undefined or null.
  6. Forgetting to prevent the form from submitting normally (refreshing the page) by using event.preventDefault().
  7. Assuming that Map and Set have the same methods as arrays, which can lead to confusion when working with these collections.
  8. Not taking advantage of Map's ability to store objects as keys or values, which can be useful in certain scenarios.
  9. Ignoring the importance of proper data validation when working with user input, which can help prevent security vulnerabilities and ensure accurate data storage.
  10. Failing to consider edge cases, such as empty Maps or Sets, or handling situations where a key or value may not exist.

Practice Questions

  1. Create a Map that stores the names of your favorite programming languages as keys and their release years as values.
  2. Write a function that takes a Map as an argument, iterates through its elements, and outputs the total sum of all values.
  3. Given the following Set: const mySet = new Set(["apple", "banana", "orange", "grape"]), write a line of code to remove the first fruit from the set.
  4. Create an interactive web application that allows users to add their names and favorite programming languages to a Map, then displays the collected data in an HTML table.
  5. Write a function that checks if a given value exists in a Set, even if it's not present as a unique element but part of multiple key-value pairs in a Map.
  6. Write a function that merges two Maps by combining their key-value pairs into a single Map.
  7. Write a function that removes all elements from a Set that are not included in another given Set.
  8. Write a function that sorts the elements of a Map based on their values, then outputs the sorted Map.
  9. Write a function that checks if two Maps have the same key-value pairs (ignoring the order of the pairs).
  10. Write a function that removes all duplicate values from a Map, keeping only the first occurrence of each value.

FAQ

Q: Can I use a Map as a traditional array?

A: While you can access values in a Map using an index (keys), it's generally not recommended because Maps are optimized for key-based lookups, and accessing elements by index can lead to slower performance.

Q: Can I use a Set as a traditional array?

A: No, Sets only store unique values and don't maintain an order like arrays do.

Q: How do I check if a Map or Set is empty?

A: You can use the size property to check the number of elements in a Map or Set, and compare it to zero (0) to determine if it's empty. For example: myMap.size === 0 or mySet.size === 0.

Q: How do I sort the elements in a Set?

A: Sets don't have a built-in method for sorting their elements, as they are designed to store unique values without any specific order. If you need to sort the elements, consider using an array instead or converting the Set to an array and sorting it before converting back to a Set.

Q: Can I loop through a Map or Set in reverse order?

A: Yes, you can loop through both Maps and Sets in reverse order by using the for...of loop with the entries() method (for Maps) or the spread operator (for Sets). Here's an example for a Map:

const myMap = new Map();
// ... (add elements to the map)
for (let [key, value] of myMap.entries().reverse()) {
console.log(`Key: ${key}, Value: ${value}`);
}

Q: How do I convert a Map to an array?

A: You can convert a Map to an array by using the Array.from() method and providing the Map's entries as an argument. Here's an example:

const myMap = new Map();
// ... (add elements to the map)
const array = Array.from(myMap.entries());
console.log(array); // Outputs [["name", "John Doe"], ["age", 30], ...]

Q: How do I convert a Set to an array?

A: You can convert a Set to an array by using the spread operator (...) or the Array.from() method. Here's an example using the spread operator:

const mySet = new Set(["apple", "banana", "orange", "grape"]);
const array = [...mySet];
console.log(array); // Outputs ["apple", "banana", "orange", "grape"]
Keyed collections (Web Development) | Web Development | XQA Learn