Map in JavaScript

Map in JavaScript

Definition: - In JavaScript, Map is a data structure that allows us to store key-value pairs and both key and value can be of any data type, like objects, functions and many more. Maps can be considered similar to objects with some key differences.

Characteristics of Map: -

  1. The keys can be of any type, not just strings or symbols like objects.

  2. The thing about Map to remember is it stores unique keys.

  3. Maps are iterable, so we can loop through them using any kind of loop like for, for of, for in, forEach etc.

  4. Maps have methods like set(), get(), clear(), detelet() etc. which we'll discuss further.

Syntax: -

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

// Assigning key-value pairs to the map
myMap.set('name','vaibhav');
myMap.set('role','web developer');

// Keys and values can be of any data type
myMap.set('fullName',{firstName:"Vaibhav", lastName:"Prajapat"});
myMap.set('greetings',()=>console.log("Hello"));

// Getting values from Map
myMap.get('name');

Methods of Map: -

  • set() - It takes two arguments and adds them to the Map as key-value pairs

  • get() - It takes the key as an argument and gives the corresponding value. If there is no key matching the argument it returns undefined.

  • has() - It takes the key as an argument and returns Boolean based on the presence of the key in the Map.

  • delete() - It takes an argument to find the matching key and delete if it exists. And if the element doesn't exist it returns false otherwise returns true.

  • clear() - It does not take any argument and simply clears the whole Map and makes it empty.

  • keys() - It returns all the keys present in the Map.

  • values() - Returns all the values present in the Map.

  • entries() - Returns every key-value pair in an array.

  • size - Returns the size of the Map.

Add values to the Map using array: -

const map1 = new Map([[1,"Iron Man"], [2,"Thor"]]);

// It will return 
// {1 => 'Iron Man', 2 => 'Thor'}

Add values to the Map via loops or other methods: -

const superHeroes = ["Iron Man", "Thor", "Hulk", "Superman"];
const map2 = new Map();

superHeroes.map((e, i) => newMap.set(i, e));

// It will return like
// {0 => 'Iron Man', 1 => 'Thor', 2 => 'Hulk', 3 => 'Superman'}

Use of Map in Web Development: -

Map can be used for different purposes like, Storing and Manipulating data, Handling for data, DOM Manipulation and so on.