Map object in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

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

 Live Demo

<!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 −

On clicking the ‘CLICK HERE’ button −

raja
Published on 17-Jul-2020 06:54:24
Advertisements