Map in ES6 JavaScript
Introduction
There is a data structure in JavaScript ES6 similar to objects that I have never fully understood. — Map
. This article mainly compares familiar objects with Map
to distinguish the characteristics and usage timing of Map
.
Syntax
// Initconst map = new Map([ [1, 'apple'], [2, 'orange'],]);
// Set - Add key and valuemap.set(3, 'banana');// Get value by keymap.get(3);// Delete by keymap.delete(3);// Clear all datamap.clear();// Check if key existsmap.has(2);// Get all keysmap.keys();// Get all valuesmap.values();// Get key-value pairsmap.entries();// Get data lengthmap.size;// Iteration for - for loopfor (const [key, value] of map) { console.log({ key, value });}// Iteration forEach - forEach loopmap.forEach((value, key) => { console.log({ key, value });});// Swap keys and valuesconst swapMap = Array.from(map).reduce((acc, [key, value]) => acc.set(value, key), new Map());
Advantages of Map Compared to Objects
- No Legacy Issues: Apart from the specially stored keys,
Map
does not have any keys, making it clearer and more concise compared toObject
.
const myMap = {};
myMap.valueOf; // => [Function: valueOf]myMap.toString; // => [Function: toString]myMap.hasOwnProperty; // => [Function: hasOwnProperty]myMap.isPrototypeOf; // => [Function: isPrototypeOf]myMap.propertyIsEnumerable; // => [Function: propertyIsEnumerable]myMap.toLocaleString; // => [Function: toLocaleString]myMap.constructor; // => [Function: Object]
Additionally, when retrieving values, for example, books[id]
, you might need to worry about whether the id
key actually exists in books
, so you need to check for existence before retrieving, like this:
// Method to check if an object has a keyif (books.hasOwnProperty(id)) {}
// Method to check if an object has a key in certain casesif (Object.prototype.hasOwnProperty.call(books, id)) {}
However, in Map
, you can directly use the corresponding method to query, and you can ensure that no extra keys exist by default. Check out the following concise syntax!
myMap.get(key);
for (const [key, value] of myMap) {}
-
Allow any type of key: The keys of a
Map
can be of any type, including objects, functions, and primitive types (strings, numbers, etc.). In contrast, the keys of an object can only be strings or symbols (Symbol). -
Explicit order: A Map retains the insertion order of key-value pairs, allowing iteration in the order they were inserted, which objects cannot guarantee. This characteristic of explicit order also makes
Map
traversal more efficient. For details, you can check out builder.io’s online quiz. -
Security: Setting user-provided
key/value
pairs on an object may allow malicious injection of crafted objects into the program (Object Injection Attacks), altering the program’s logic or executing unintended operations, while usingMap
methods can safely avoid this situation.
Disadvantages of Map Compared to Objects
- Learning curve: Although
Map
is simple to use, it is less frequently encountered, so those unfamiliar with it may incur additional learning costs. - Memory overhead: Due to the implementation details of Map, it typically consumes more memory than objects when storing the same number of key-value pairs.
- JSON support: Objects can be directly converted to JSON format, while Maps require additional processing to serialize to JSON format.
// Convert Object to JSONconst obj = { key: 'value' };const jsonString = JSON.stringify(obj);
// Convert Map to JSONconst map = new Map();map.set('key', 'value');
// Needs to be converted to an object or array before converting to JSONconst mapToObject = Object.fromEntries(map);const mapToJsonString = JSON.stringify(mapToObject);
When to Use
In summary, Map
can be considered as an object for frequent read and write operations, offering better performance and clearer syntax, while objects can be used to store fixed key-value pairs when frequent read and write is not needed.
Further Reading
- Map - mdn
- Use Maps more and Objects less - builder.io
- You Should Use Maps and Sets in JS - Syntax
- Map vs Object in JavaScript - Leigh Halliday