Introduction to Maps in JavaScript

Introduction to Maps in JavaScript

Maps are little heard of Data Structure in JavaScript. They were introduced in ES2015. Maps are similar to Objects but have some differences, let's know more about them.

Maps are a collection of data items stored in key-value pairs, just like Objects. But the main difference is that Map allows keys to be of any data type (unlike Objects where the key can only be a string).

// object
const details = {
    firstName : "John",
    lastName: "Doe",
    age: 19,
    licence: true,
};

How to initialize Maps

Maps can be created by use of the new keyword, like so:

const theMap = new Map();

The above Map is empty, so we can initialize a Map using a built-in method: map.set(key, value). You can chain these methods so you don’t have to use the name of the map over and over again (as shown in 2nd part)

// Without chaining
myDetails.set("firstName", "John");
myDetails.set("lastName", "Doe");
myDetails.set("age", 19);

/* the above method can get exhausting, hence Maps allow us to chain methods while declaring them. */
const flight = new Map();
flight
  .set('status', 'Delayed')
  .set('passenger', 'Mary Jones')
  .set(true, '11B')
  .set('flightName', 'Airbus 320');

We can initialize Maps with help of arrays as well. The array contains sub-arrays, with each sub-array having a key and the value.

const detailMap = new Map([
  ['firstName', 'John'],
  ['lastName', 'Doe'],
  ['age', 19],
  [true, 'licence'],
]);

console.log(detailMap);
/* Map(4) {"firstName" => "John", "lastName" => "Doe", "age" => 19, true => "licence"} */

We can convert an existing Object to Map, using the .entries() method (since the elements are in key-value form).

// object
const details = {
    firstName : "John",
    lastName: "Doe",
    age: 19,
    licence: true,
}

// convert the Object to Map
const myDetails = new Map(Object.entries(details));
console.log(myDetails);
/* Map(4) {"firstName" => "John", "lastName" => "Doe", "age" => 19, "licence" => true} */

Map methods

Maps have in-built methods that can be used to manipulate data:

  • map.set(key, value); to add data to maps (as seen above)
  • map.get(key); returns the value by the key (shows undefined if key doesn't exist)
  • map.has(key); check if key exists, returns true if exists
  • map.delete(key); removes the value by the key
  • map.size; returns the count of elements in map
  • map.clear(); removes everything from map

Iteration in Maps

Remember Maps are iterable, unlike Objects which cannot be iterated directly.

We can iterate using the for..of or for..each loop. We can destructure the iterator into key, value without the need for the .entries() method.

We can also use

  • Map.keys() - to iterate through the keys
  • Map.values() - to iterate through the values
const colorLike = new Map([
    ['name', 'Naina'],
    [1, 'Red'],
    [2, 'Blue'],
    [3, 'Yellow'],
]);

console.log(`${colorLike.get('name')} likes the following colors:`);
for (const [key, value] of colorLike) {
    if(typeof key === 'number')
        console.log(value);
}
/*
Naina likes the following colors:
Red
Blue
Yellow
*/

//  Following will log the keys of the Map
for (const key of colorLike.keys()) {
 console.log(key);   
}
/*
name
1
2
3
*/

Maps vs Objects

You might think, why use Objects if Maps exist. Maps are lesser-known collections that were introduced under modern JavaScript, hence Objects have been the go-to way for a long time. They are easier to write and access with the dot (.) and brackets([]) operator, hence they are much more popular and easy to use.

Moreover, we cannot define methods (functions) in Maps like in Objects, which is an essential feature used quite often.

So Maps are used in cases where we need better performance Or when the keys need to be of a different data type. Also, since Maps are easier to iterate over than Objects, they do have some use in programming.

Maps in use

const details = new Map();
details
  .set('name', 'Jessy')
  .set('age', 19)
  .set(true, 'has Licence')
  .set(false, "doesn't have licence");

                                                               // true
console.log(details.get('name') + ' ' + details.get(details.get('age') >= 18));
// Jessy has Licence

✔Summary

  • Maps are collection of keyed data items, which allow keys to be of any data-type.
  • Maps have some in-built methods which we can use to manipulate data, like, map.get(), map.set(), map.size etc.
  • Maps are iterable
  • Maps can be used over Objects where better performance is required or when the keys need to be of different type.

I hope you find the article helpful! Thank you for reading! Comment down your feedback and suggestions, I am always open to it! 😃

You can always reach out to me at LinkedIn | Twitter 🙋‍♀️