Search⌘ K
AI Features

Tip 13: Update Key-Value Data Clearly with Maps

Explore how to use JavaScript Maps to manage key-value data clearly and efficiently. Understand adding, removing, and clearing entries with specialized Map methods. Learn why Maps offer better flexibility and cleaner code compared to objects, especially for frequently changing collections. This lesson equips you to improve your code clarity and maintainability using Maps.

In Tip 10, Use Objects for Static Key-Value Lookups, you learned that you should only use objects deliberately and not as a default collection. Now you’re going to get a chance to look at an alternative: Map.

Map

Map is a special kind of collection that can do certain things very easily. The Mozilla Developer Network has a nice list of circumstances where Map is a better option for a collection than a plain object. I encourage you to read the full list, but this tip examines two specific situations:

  • Key-value pairs are frequently added or removed.

  • A key isn’t a string.

In the next tip, you’ll see another big advantage: using Map for iterating over collections. For now, you just need to be familiar with adding or removing values to maps.

Adding & removing key-value pairs: Example

First, think about what it means that key-value pairs are frequently added and removed. Consider a pet adoption website. The site has a list of all the adorable dogs that need homes. Because people have different expectations of their pets (some want big dogs, some like certain breeds), you’ll need to include a way to filter the animals.

You’ll start off with a collection of animals:

Node.js
const dogs = [
{
name: 'max',
size: 'small',
breed: 'boston terrier',
color: 'black'
},
{
name: 'don',
size: 'large',
breed: 'labrador',
color: 'black'
},
{
name: 'shadow',
size: 'medium',
breed: 'labrador',
color: 'chocolate'
}
]

The collection of all dogs is an array, which makes sense because the shape of each item in the collection is the same.

You’ll need to create one more collection: your list of applied filters. The filters will be a ...