Map in javascript

Rumman Ansari   Software Engineer   2024-02-09 04:31:28   25 Share
Subject Syllabus DetailsSubject Details
☰ Table of Contents

Table of Content:


In JavaScript, the Map object is a built-in data structure that allows you to store key-value pairs. It is similar to an object but provides some additional features and advantages. Here's an example of how you can use a Map:


// Creating a Map
let myMap = new Map();

// Adding key-value pairs
myMap.set('name', 'Rumman');
myMap.set('age', 25);
myMap.set('isStudent', true);

// Getting values
console.log(myMap.get('name'));       // Output: Rumman
console.log(myMap.get('age'));        // Output: 25
console.log(myMap.get('isStudent'));  // Output: true

// Checking if a key exists
console.log(myMap.has('gender'));     // Output: false

// Deleting a key-value pair
myMap.delete('isStudent');

// Iterating over key-value pairs
for (let [key, value] of myMap) {
    console.log(`${key}: ${value}`);
}
// Output:
// name: Rumman
// age: 25

Here are some key points about Map:

  1. Keys can be of any data type: Unlike object keys which are converted to strings, Map keys can be of any data type, including objects and primitive values.

  2. Order of insertion is maintained: Map objects maintain the order of key-value pairs based on the order of insertion.

  3. Iterable: You can easily iterate over the keys or values of a Map using loops or methods like forEach.

  4. Size property: The size property indicates the number of key-value pairs in the Map.

Using Map is especially useful when you need to associate values with keys and perform operations like adding, deleting, and checking for the existence of keys in a more straightforward and reliable manner compared to using plain objects.