Javascript Maps

The Javascript Map object is an interesting data structure. It has characteristics of both objects and arrays. In Javascript an object is a data structure defined by keys made of strings and properties that can be of any data type. A Map has the key value pair data structure with a few advantages. The keys in a Map can be of any data type. Maps also have functions built in for enumeration and size. Maps also track insertion order similar to arrays.

                
                    // create a map
                    const map = new Map();
                    
                    // Add values to the map
                    map.set('name', 'My Blog');
                    map.set('type', 'blog');
                    map.set('writer', 'Hans Pieper');
                
            

In Javascript an object always stores its keys as strings, even if given a primitve or object, it will internally convert the key to a string. Map objects will maintain the data type of the key as given. Maps also have a number of useful properties and methods. For instance Maps have a size property, similar to an array's length. This is useful compared to an object where there is no built in means to easily assess its size. Maps can also be searched by the has(key) method.

                
                    // Create an empty object
                    const newObj = {};

                    // add a property. Note, passing the key as a number.
                    newObj[315] = 'My Street Address';

                    // It returns true because the number 315 got converted into the string '315' internally!
                    console.log(newObj[315] === newObj['315']);
                
            

When should a Map be used instead of an object? A Map would be more useful than an object in an instance where using objects as keys would helpful in the data structure. Another use for maps is when the order of entries are important. Objects do not maintain the order of their entries. Maps provide flexibility without relying on an external library, because we do not find methods like has(), values(), delete(), or a property like size with a regular object. Map makes this easy for you by providing all these methods by default.

                
                    //Convert an object to a Map
                    const address = {
                        'Joe': 'LaCrosse',
                        'Steve': 'LaCrecent',
                        'Jill': 'Onalaska'
                    };
                    
                    const addressMap = new Map(Object.entries(address));

                    //Convert a Map to an object
                    const newAddress = Object.fromEntries(addressMap);