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.
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.
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
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}`);});
Method | Description |
---|---|
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 |
size | Number of entries in the Map |
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 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: 0console.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.
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.
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.
Map
Use a Map
when you:
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.
Quick Links
Legal Stuff
Social Media