HomeAbout Me

πŸ”₯ Mastering `Map` in JavaScript: The Underrated Power Tool for Structured Data

By Daniel Nguyen
Published in Javascript
March 30, 2025
1 min read
πŸ”₯ Mastering `Map` in JavaScript: The Underrated Power Tool for Structured Data

When dealing with key-value pairs in JavaScript, one of the most flexible tools you can use is the Map object. Whether you’re organizing structured data, implementing caches, or creating fast lookups with complex keys, Map provides features that traditional objects ({}) can’t match.


πŸ” What Is a Map?

A Map is a collection of keyed data items, just like an object. But unlike plain objects, Map allows keys of any type and maintains the insertion order of items.

βœ… Key Features:

  • Keys can be any type (objects, functions, primitives)
  • Maintains insertion order
  • Iteration is easy and consistent
  • Cleaner semantics for key-value storage

✍️ Basic Usage with Map

const userRoles = new Map();
userRoles.set("alice", "admin");
userRoles.set("bob", "editor");
userRoles.set("charlie", "viewer");
console.log(userRoles.get("bob")); // 'editor'
console.log(userRoles.has("alice")); // true

πŸ” Loop through a Map

You can loop through a Map using a for...of loop:

for (const [user, role] of userRoles) {
console.log(`${user} => ${role}`);
}

Or use other built-in iterator methods:

userRoles.forEach((role, user) => {
console.log(`${user} is a ${role}`);
});

πŸ” Common Methods for Map

MethodDescription
set(key, value)Adds or updates an entry
get(key)Retrieves a value by key
has(key)Checks if a key exists
delete(key)Removes an entry by key
clear()Removes all entries
sizeNumber of entries in the Map

πŸ§ͺ Real-World Example: Counting Word Frequency

const sentence = "hello world hello map";
const words = sentence.split(" ");
const frequencyMap = new Map();
for (const word of words) {
frequencyMap.set(word, (frequencyMap.get(word) || 0) + 1);
}
console.log(frequencyMap);
// Map { 'hello' => 2, 'world' => 1, 'map' => 1 }

Maps are great for counting occurrences, caching, or tracking states by complex keys.


🧩 LeetCode Example: First Unique Character in a String

LeetCode Problem: 387. First Unique Character in a String

var firstUniqChar = function(s) {
const map = new Map();
for (const char of s) {
map.set(char, (map.get(char) || 0) + 1);
}
for (let i = 0; i < s.length; i++) {
if (map.get(s[i]) === 1) {
return i;
}
}
return -1;
};
// Example:
console.log(firstUniqChar("leetcode")); // Output: 0
console.log(firstUniqChar("loveleetcode")); // Output: 2

In this example, Map is used to count the frequency of each character and then identify the first character with a count of 1.


πŸ” Convert Object to Map (and vice versa)

const obj = { a: 1, b: 2 };
const map = new Map(Object.entries(obj));
const backToObject = Object.fromEntries(map);

This makes it easy to switch between JSON-friendly objects and more powerful maps.


🚫 Things to Keep in Mind

  • Objects and arrays are compared by reference, not value:

    const map = new Map();
    const objKey = { id: 1 };
    map.set(objKey, "data");
    console.log(map.get({ id: 1 })); // undefined β€” different reference
  • Map is not JSON serializable by default. You’ll need to convert it to an object or array before sending/storing.


🎯 When to Use Map

Use a Map when you:

  • Need key-value pairs with non-string keys
  • Need to preserve insertion order
  • Want cleaner and more powerful alternatives to plain objects
  • Are implementing caches, lookups, or memoization

πŸ”š Final Thoughts

The Map object is a versatile and powerful addition to your JavaScript toolbox. It offers a smarter way to handle key-value data, going beyond what plain objects provide. If you haven’t already started using Map, now’s the time to give it a try.


πŸ“Œ Pro tip: Use Map when you need structured key-value data with flexibility and performance β€” especially when object keys just don’t cut it.


Tags

#Javascript

Share

Previous Article
πŸ“˜ Section 27: Performing Integration in Project Management

Table Of Contents

1
πŸ” What Is a Map?
2
✍️ Basic Usage with Map
3
πŸ” Common Methods for Map
4
πŸ§ͺ Real-World Example: Counting Word Frequency
5
🧩 LeetCode Example: First Unique Character in a String
6
πŸ” Convert Object to Map (and vice versa)
7
🚫 Things to Keep in Mind
8
🎯 When to Use Map
9
πŸ”š Final Thoughts

Related Posts

How `this` behaves in JavaScript
April 24, 2025
1 min
Β© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media