Map Data Types in JavaScript

JavaScript2 min read
Map Data Types in JavaScript
javascriptmap data typedata types

In JavaScript, the map data type allows us to store and retrieve key-value pairs, similar to objects. The key difference between objects and maps is that in objects, the key must be of string type, whereas in a map, both the key and value can be of any type.

Map Data Types in JavaScript

  • In JavaScript, the map data type allows us to store and retrieve key-value pairs, similar to objects.
  • The key difference between objects and maps is that in objects, the key must be of string type, whereas in a map, both the key and value can be of any type.

Creating a Map

  • To create a map, we use the new Map() constructor.
let userData = new Map();

Adding Key-Value Pairs

  • To add key-value pairs to a map, we use the set() method. The first parameter is the key, and the second parameter is the value.
userData.set("name", "Coders"); userData.set(1, "John"); userData.set(true, "Active");
  • In this example, we add:
    • A string key "name" with the value "Coders",
    • A number key 1 with the value "John",
    • A boolean key true with the value "Active".

Accessing Values

  • To retrieve values from a map, we use the get() method and pass the corresponding key.
document.write(userData.get("name")); // Output: Coders
  • Here, we retrieve the value associated with the key "name", which is "Coders".

Modifying Map Data

  • Maps allow us to update the value of a key using the set() method again:
userData.set("name", "Developers"); document.write(userData.get("name")); // Output: Developers
  • In this case, the value for the key "name" is updated to "Developers".

Iterating Over a Map

  • We can iterate through the keys and values of a map using various methods like forEach() or for...of.
userData.forEach((value, key) => { document.write(`${key} : ${value} <br>`); }); // Output: // name : Developers // 1 : John // true : Active
  • This loop iterates over the map and prints both keys and values.

Summary:

  • Maps in JavaScript allow us to store key-value pairs where both keys and values can be of any type.
  • We use set() to add or modify key-value pairs, and get() to retrieve values based on their keys.
  • Maps offer iteration methods like forEach() to loop through all key-value pairs.
  • Unlike objects, maps allow non-string keys.