HomeAbout Me

๐Ÿ”ฅ Mastering `Map` in JavaScript: The Underrated Power Tool for Structured Data

By Daniel Nguyen
Published in Javascript
March 30, 2024
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
Add Styles

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, 2024
1 min
ยฉ 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media