DEV Community

M.Ark
M.Ark

Posted on • Edited on

Maps in JavaScript

Maps provide a key-based lookup while retaining the type of the key, unlike objects that coerce keys into strings. They offer a constructor for creating new instances.

Maps provide a way to look up values based on keys while preserving the key types, unlike objects which convert keys to strings. They're instantiated using a constructor and offer an extensive API for managing key-value pairs.
Maps are invaluable when you need to associate data with keys in JavaScript, especially in scenarios where:

  1. Preservation of Key Type is crucial: Unlike objects, maps retain the type of keys you use. This is essential when dealing with different types of data, ensuring that keys remain consistent without being inadvertently coerced or converted.

  2. Flexible Key Types: Maps allow for a wider range of key types compared to objects, where keys are typically coerced to strings. This flexibility enables you to use complex data types, objects, or even functions as keys, which may not be feasible with objects.

  3. Efficient Key-Value Pair Management: Maps provide a comprehensive API for adding, updating, and deleting key-value pairs. Their fluent interface makes it easy to perform these operations without verbose syntax, enhancing code readability and maintainability.

  4. Iteration and Order: Maps maintain the order of key-value pairs, which can be crucial in scenarios where the order of insertion or retrieval matters. Additionally, maps offer efficient methods for iterating over keys, values, or entries, providing flexibility in data processing.

  5. Avoiding Prototype Pollution: Maps are immune to prototype pollution, a vulnerability where unwanted properties can be unintentionally added to all objects of a given type. By using maps, you mitigate the risk of unintended property additions and maintain data integrity.

  6. Complex Data Structures: Maps are essential for modeling complex data structures such as graphs, trees, or hash tables. They offer a clear and efficient way to represent relationships between entities, making them indispensable in data manipulation and algorithmic implementations.

  7. Working with External Data: When interfacing with external APIs or libraries that return data in key-value pairs, maps provide a natural and convenient way to store and manipulate this data. They offer a consistent and standardized interface for working with such data structures.

Unlike arrays and objects, maps lack a literal for construction, impacting their serializability. However, they offer a comprehensive API for adding, updating, and deleting key-value pairs.

const obj = {};
const map = new Map();

map.set('string', 'is a string');
map.set(true, 'is a boolean');
map.set(1, 'is a number').set(obj, 'is an object');

console.assert(map.has(1));
console.assert(map.get(obj) === 'is an object');

map.set(1, 'overrides first');

console.assert(map.get(1) === 'overrides first');
console.assert(map.delete('string'));
console.assert(map.has('string') === false);
console.assert(map.delete({}) === false);

Enter fullscreen mode Exit fullscreen mode

Let's break down the code:

① Creating an empty map.

② Adding key-value pairs to the map: 'string' maps to 'is a string', true maps to 'is a boolean'.

③ Chaining set() method calls to add more key-value pairs: 1 maps to 'is a number' and obj (an empty object) maps to 'is an object'.

④ Asserting whether the map has the key 1.

⑤ Asserting whether the value associated with the obj key is 'is an object'.

⑥ Overriding the value associated with the key 1.

⑦ Asserting that the value associated with the key 1 is 'overrides first'.

⑧ Deleting the key 'string' from the map.

⑨ Asserting that attempting to delete an object {} (different from obj) from the map returns false.

The Map API provides us with all we need to work with keys and values.
The set API being fluent certainly proves to be a worthy ally, allowing to avoid some of the verbosity that results if that were not the case.
Collisions are handled as we might expect, and
finally, we can use the delete API to remove a key-value pair from the map, which returns true if the key was indeed deleted from the map.

Top comments (0)