[JavaScript ES6] Map Object in JavaScript - How to Use It. Explained with Examples.
Table of contents
Explore how to use Map Object and its useful methods. With Map Object, you can program more efficiently when dealing with an object.
Introduction
Even though Map Object does a similar thing as what an object does, it has distinct advantages.
It allows your key to hold any data type, such as an array, number and so on. On the other hand, an object only allows strings as a key.
It remembers the order of insertion order of the keys.
It has a property called size that represents the size of the map.
Map Object
There are several methods/properties that you want to know when you use Map Object.
set() to add a key-value pair
get() to retrieve a value by using a key name.
has() to check if a certain key exists.
delete() to delete a key-value pair.
size property to check the size of your map.
clear() to clear out your map.
let personMap = new Map();
// set()
personMap.set("name", "John");
personMap.set("email", "john@gmail.com");
personMap.set("gender", "male");
console.log(personMap);
// {'name' => 'John', 'email' => 'john@gmail.com', 'gender' => 'male'}
// get()
console.log(personMap.get("name")); // John
// has()
console.log(personMap.has("email")); // true
console.log(personMap.has("address")); // false
// delete() if no key is found, it returns false. If found, returns true.
console.log(personMap.delete("gender")); // true
console.log(personMap.delete("address")); // false
console.log(personMap); // {'name' => 'John', 'email' => 'john@gmail.com'}
// size
console.log(personMap.size); // 2
// clear()
personMap.clear(); // clears out everything.