Map in javascript
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:
-
Keys can be of any data type: Unlike object keys which are converted to strings,
Mapkeys can be of any data type, including objects and primitive values. -
Order of insertion is maintained:
Mapobjects maintain the order of key-value pairs based on the order of insertion. -
Iterable: You can easily iterate over the keys or values of a
Mapusing loops or methods likeforEach. -
Size property: The
sizeproperty indicates the number of key-value pairs in theMap.
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.