Lesson 14 of 33
Maps and Sets
Use Map for key-value lookup where the key can be any value, and Set for collections of unique items, and learn when to reach for them over objects and arrays.
For a long time, JavaScript developers used plain objects for storing key-value pairs and arrays for lists of data. Objects and arrays will cover most of what you do, but both have limits that show up as your programs grow or as you need more specific behaviour.
ES6 (modern JavaScript) introduced two more built-in data structures: Map and Set.
Map Structure
Key-value dictionary where keys can be ANY data type (objects, functions, numbers, booleans). Remembers insertion order and has a built-in .size property.
Set Structure
Collection of unique values. Ignores duplicate entries and provides fast .has() checks.
Think of a Map as a dictionary where the word being looked up can be any value at all, even an object or a function. Think of a Set as a guest list where every name appears exactly once, however many times you write it down.
Working with Map
A Map is an ordered collection of key-value pairs, similar to a plain object, but with big advantages:
- Any Data Type as Keys: Plain objects only allow strings (and symbols) as keys. A
Maplets you use numbers, booleans, objects, or even DOM elements as keys. - Built-in Size: Plain objects do not tell you how many properties they hold without calling
Object.keys(obj).length. AMaphas a quick.sizeproperty. - Guaranteed Iteration Order: A
Mapalways remembers the exact order in which keys were inserted.
Basic Map operations
// Create a new Map
const userRoles = new Map();
// Set key-value pairs using .set(key, value)
const userAlice = { id: 1, name: "Alice" };
const userBob = { id: 2, name: "Bob" };
userRoles.set(userAlice, "Admin");
userRoles.set(userBob, "Student");
// Read values using .get(key)
console.log(userRoles.get(userAlice)); // "Admin"
// Check if a key exists using .has(key)
console.log(userRoles.has(userBob)); // true
// Check total entries
console.log(userRoles.size); // 2
// Delete an entry with .delete(key)
userRoles.delete(userBob);
console.log(userRoles.size); // 1Notice that we used the object userAlice itself as a key in userRoles. Try doing that with a plain object and it converts the key to the text string "[object Object]", so every object key collides with every other one.
Working with Set
A Set is a collection of values where every item must be unique. If you try to add an item that is already inside the Set, it simply ignores it.
Sets are great for:
- Keeping track of unique items (like unique user IDs, tags, or visited pages).
- Removing duplicates from an array in a single line of code.
- Checking whether an item exists quickly using
.has().
Basic Set operations
// Create a new Set
const uniqueTags = new Set();
// Add items using .add(value)
uniqueTags.add("javascript");
uniqueTags.add("web");
uniqueTags.add("javascript"); // Duplicate, ignored automatically
console.log(uniqueTags.size); // 2
// Check existence
console.log(uniqueTags.has("web")); // true
console.log(uniqueTags.has("python")); // false
// Delete an item
uniqueTags.delete("web");Removing duplicates from an array
One of the most common tasks in web development is removing duplicate items from a list. With Set, it takes just one line:
const numbersWithDuplicates = [1, 2, 2, 3, 4, 4, 4, 5];
// Convert Array -> Set (removes duplicates) -> Array
const cleanNumbers = [...new Set(numbersWithDuplicates)];
console.log(cleanNumbers); // [1, 2, 3, 4, 5]Try it yourself
Add another "coding" to rawTags and confirm the unique count does not move. Then set a score for player1 twice and check that the Map still holds one entry per key.
Quick comparison
| Feature | Object | Map | Array | Set |
|---|---|---|---|---|
| Key Type | Strings & Symbols | Any Type | Indexed Numbers | N/A (Values only) |
| Duplicates | Keys must be unique | Keys must be unique | Allows duplicates | Guaranteed unique values |
| Check Size | Object.keys(o).length | .size | .length | .size |
| Lookup Speed | Fast | Fast | Search with .includes() | Fast (.has()) |
What about WeakMap and WeakSet?
JavaScript also provides WeakMap and WeakSet. The "weak" part means they hold references to objects weakly. If an object stored inside a WeakMap or WeakSet has no other references in your code, JavaScript's garbage collector can safely delete it from memory. This is handy for advanced memory management when attaching metadata to DOM elements or private object data.
What to remember
Map gives you key-value storage where keys can be any data type, and .size is built in. Set holds a collection of unique items, and turning an array into a Set and back with [...new Set(array)] removes duplicates in one line.
Check yourself
4 questions · pass 3/4 to unlock Handling Errors and Debugging
1.How does a JavaScript Map differ from a plain JavaScript Object?
2.What happens when you add a duplicate item to a Set using .add()?
3.Which of these is the fastest way to remove duplicate elements from an array?
4.Why would you use a WeakMap instead of a regular Map?
4 left to answer