JavaScript Map Size Property

November 8, 2023

What is the JavaScript Map Size property?

The JavaScript Map object's size property returns the number of key/value pairs in the map. It provides an efficient way to determine the count without the need to iterate over the entire map.

It’s useful for things like:

  • Validating the number of entries before performing operations.
  • Checking map capacity against thresholds.
  • Implementing logic that depends on the count of items in the map.

The size property of a Map object in JavaScript is read-only and reflects the number of elements in a Map. It's a straightforward way to get the count of entries, where each entry is a key-value pair.

How to use the size property

To access the size property, you simply reference it on your Map instance. Here's an example:

let myMap = new Map(); myMap.set('key1', 'value1'); myMap.set('key2', 'value2'); console.log(myMap.size); // Outputs: 2

Size vs length

Unlike arrays, where you use length to get the number of elements, for a Map you must use size. This is because Map objects maintain the insertion order of elements and are a part of the ES6 specification.

How to Check if a Map is empty

You can check if a Map is empty by comparing its size property to 0:

if(myMap.size === 0) { console.log('Map is empty'); }

Limitations and considerations

The size property is dynamic. If you add or remove items from the map, the size will update accordingly. Keep in mind that size is a property, not a method, so you do not call it with parentheses.

Ship faster, worry less with Basedash

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

Dashboards and charts

Effortlessly make charts and create a space for your team to work together towards shared goals and metrics.

User CRM

SQL composer with AI

Admin panel

Screenshot of a users table in a database. The interface is very data-dense with information.