JS Capsules: Maps

JS Capsules: Maps

Featured on daily.dev

Introduction

A Map is a collection of elements, where each element is stored as a key: value pair.

By this definition, it can seem similar to an Object, but while a Map can accept any data type (both primitive values and objects) as its key, an Object’s key can only be a String or Symbol.

You can describe a Map as combining the best parts of Arrays and Objects. It was introduced in JavaScript’s ES6 specification as a better way to work with keys and values.

Syntax

new Map([x])
// "x" represents iterable elements stored as key:value pairs
// When "x" is not specified, the Map starts out empty

For example, let us create a Map to store some user details:

const user = new Map([
  ['First Name', 'Divine'],
  ['Last Name', 'Orji'],
  ['Age', 24],
  [false, 'Dance'],
]);

console.log(user);

/*
Map(4) {
  'First Name' => 'Divine',       
  'Last Name' => 'Orji',
  'Age' => 24,
  false => 'Dance'
}
*/

As you can see in this example, the Map looks like a 2D array, and each second level contains two elements - [key, value].

You can also see that the key can be of any data type. Here we have a couple of Strings and a Boolean.

Differences between Map and Object

Some differences between a Map and an Object include:

  • Key types: A Map's key can be of any data type, but an Object's key can only be a String or a Symbol.
  • Accidental keys: A Map has no default keys and can only contain the keys you explicitly put into it, but an Object prototype has default keys that could clash with your keys.
  • Size: You can quickly get the number of items in a Map using its size property, but you have to count manually in an Object.
  • Performance: It is much easier to remove or add key: value pairs in a Map than in an Object.

Map properties and methods

Properties

Map.prototype.size: This returns the number of items in a Map.

From our previous example:

console.log(user.size)
// 4

Methods

Here are some methods you can use with Map:

Map.prototype.set(key, value): Adds a new key: value entry to your Map.

user.set('Pet', 'Gary');
console.log(user);

/*
Map(5) {
  'First Name' => 'Divine',
  'Last Name' => 'Orji',   
  'Age' => 24,
  false => 'Dance',        
  'Pet' => 'Gary'
}
*/

Map.prototype.has(key): Checks if the specified key exists in your Map.

console.log(user.has('Age'));
// true

Map.prototype.get(key): Gets the value associated with the specified key, or returns undefined if the key does not exist.

 console.log(user.get('Pet'));
// Gary

console.log(user.get('House'));
// undefined

Map.prototype.delete(key): Deletes the specified key and its value, then returns true. If the key does not exist, it returns false.

console.log(user.delete('Age'));
// true

console.log(user);
/*
Map(4) {
  'First Name' => 'Divine',
  'Last Name' => 'Orji',   
  false => 'Dance',        
  'Pet' => 'Gary'
}
*/

console.log(user.delete('House'));
// false

Map.prototype.entries(): Returns an object with each key: value pair stored as an array.

console.log(user.entries());

/*
[Map Entries] {
  [ 'First Name', 'Divine' ],     
  [ 'Last Name', 'Orji' ],        
  [ false, 'Dance' ],
  [ 'Pet', 'Gary' ]
}
*/

Map.prototype.keys(): Returns an object with all the keys in your Map.

console.log(user.keys());
// [Map Iterator] { 'First Name', 'Last Name', false, 'Pet' }

Map.prototype.values(): Returns an object with all the values in your Map.

console.log(user.values());
// [Map Iterator] { 'Divine', 'Orji', 'Dance', 'Gary' }

Map.prototype.forEach(): Executes a callback function on each entry in your Map.

user.forEach((value) => {
  console.log(value);
});

/*
Divine
Orji
Dance
Gary
*/

Map.prototype.clear(): Deletes all entries in your Map.

user.clear()

console.log(user)
// Map(0) {}

Conclusion

In this article, you learned about the Map and how to use it. Picking the proper data structure for your project can give you more flexibility and ease when handling data, and using this knowledge, you will come closer to making the right choice.

To learn more about Maps, check out these resources below.

Feel free to send me a message on Twitter if you love this article or have questions. Thanks!

Resources