[JavaScript ES6] Map Object in JavaScript - How to Use It. Explained with Examples.

·

2 min read

[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.

  1. 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.

  2. It remembers the order of insertion order of the keys.

  3. 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.

  1. set() to add a key-value pair

  2. get() to retrieve a value by using a key name.

  3. has() to check if a certain key exists.

  4. delete() to delete a key-value pair.

  5. size property to check the size of your map.

  6. 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.

Did you find this article valuable?

Support Jay's Dev Blog by becoming a sponsor. Any amount is appreciated!