Computer >> Computer tutorials >  >> Programming >> Javascript

Map object in JavaScript.


Map object was introduced in ES6 and is a collection of elements that are key and value pair. A key or value in a map can be an object or a primitive value.

Following is the code for map object in JavaScript −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Map object in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to create and display a map object</h3>
<script>
   let resultEle = document.querySelector(".result");
   let map1 = new Map([
      ["name", "Rohan Sharma"],
      ["age", 14],
      ["class", 9],
   ]);
   document.querySelector(".Btn").addEventListener("click", () => {
      for (let [key, value] of map1) {
         resultEle.innerHTML += key + " = " + value + "<br>";
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

Map object in JavaScript.

On clicking the ‘CLICK HERE’ button −

Map object in JavaScript.