• JavaScript Video Tutorials

JavaScript - Map.size Property



The Map.size property in JavaScript is used to return a integer value as a result that represents the number elements in a Map object. This property is a read-only property. In other words, we cannot directly change the size property of a Set object using an accessor function because it is not defined to allow such changes.

Syntax

Following is the syntax of JavaScript Map.size property −

Map.size

Return value

This property returns number of elements in Map object.

Examples

Example 1

In the following example, there are three elements present in the Map object, and we are computing the size of this map using the JavaScript Map.size property −

<html>
<body>
   <script>
      const map = new Map();
      map.set('o', 'orange');
      map.set('g', 'grape');
      map.set('p', 'pineapple');
      document.write("Size of this map: ", map.size);
   </script>
</body>
</html>

If we execute the above program, it returns 3 as result.

Example 2

In this example, the Map object does not have any elements it −

<html>
<body>
   <script>
      const map = new Map();
      document.write(map.size);
   </script>
</body>
</html>

If we execute program, it returns 0 as result.

Example 3

Here, we are trying to "set" the size of an empty (0) Map object to 10 −

<html>
<body>
   <script>
      const map = new Map();
      map.size = 10
      document.write(map.size);
   </script>
</body>
</html>

If we execute program, it returns 0 as result because "size" property is read-only and cannot be changed or modified.

Advertisements