It???s 2023. Start using JavaScript Maps and Sets

As a JavaScript developer, you are probably familiar with the two most commonly used data structures, Arrays and Objects. They are both extremely versatile and powerful however, two more options are often overlooked: Maps and Sets. Let’s explore how they can make your code more efficient and easier to read.

Maps

Maps are similar to Objects in that they store key-value pairs. However, unlike Objects, Maps allow any type of value to be used as a key, including objects and functions. This makes them much more flexible than Objects, especially when you need to store complex data structures.

To create a Map, you can use the Map constructor:

const myMap = new Map();

You can also initialize a Map with an array of key-value pairs:

const myMap = new Map([
 ["key1", "value1"],
 ["key2", "value2"]
]);

To add a key-value pair to a Map, you can use the set() method:

myMap.set("key3", "value3");

To retrieve a value from a Map, you can use the get() method:

const value = myMap.get("key3");

Maps also have other useful methods, such as has() to check if a key exists in the Map, delete() to remove a key-value pair, and clear() to remove all key-value pairs and, of course, the very useful .size which is not available in objects.

Website