It’s 2023. Start using JavaScript Maps and Sets

<p>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&rsquo;s explore how they can make your code more efficient and easier to read.</p> <h2><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" rel="noopener ugc nofollow" target="_blank">Maps</a></h2> <p>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.</p> <p>To create a Map, you can use the Map constructor:</p> <pre> const myMap = new Map();</pre> <p>You can also initialize a Map with an array of key-value pairs:</p> <pre> const myMap = new Map([ [&quot;key1&quot;, &quot;value1&quot;], [&quot;key2&quot;, &quot;value2&quot;] ]);</pre> <p>To add a key-value pair to a Map, you can use the&nbsp;<code>set()</code>&nbsp;method:</p> <pre> myMap.set(&quot;key3&quot;, &quot;value3&quot;);</pre> <p>To retrieve a value from a Map, you can use the&nbsp;<code>get()</code>&nbsp;method:</p> <pre> const value = myMap.get(&quot;key3&quot;);</pre> <p>Maps also have other useful methods, such as&nbsp;<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has" rel="noopener ugc nofollow" target="_blank">has()</a></code>&nbsp;to check if a key exists in the Map,&nbsp;<code>delete()</code>&nbsp;to remove a key-value pair, and&nbsp;<code>clear()</code>&nbsp;to remove all key-value pairs and, of course, the very useful&nbsp;<code>.size</code>&nbsp;which is not available in objects.</p> <p><a href="https://fadamakis.com/be-cool-start-using-javascript-maps-and-sets-df613e8c6ed5">Website</a></p> <p>&nbsp;</p>