Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Collections

Map.prototype.size

Reference for the Map size property: how many entries a map holds, why it is read-only, how it differs from array length and how to count object keys.

map.size is a read-only property that returns the number of key-value entries currently in the map. It is updated automatically by set(), delete() and clear(), and reading it is fast regardless of how large the map is.

size is an accessor on Map.prototype, not a data property you can assign to. It is also the name used by Set. Arrays use length instead.

JavaScript
const m = new Map([["a", 1], ["b", 2]]);
m.size;   // 2

Try it

JS Size follows the contents

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS size versus length

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
map.size

Value: a non-negative integer, the number of entries. It counts keys, so each key is counted once, and an entry whose value is undefined still counts.

Exceptions: reading size on an object that is not a Map (for example Map.prototype.size itself) throws a TypeError.

Usage notes

  • It is read-only. Assigning to it is ignored in sloppy mode and throws a TypeError in strict mode (modules and classes are strict). To shrink a map, call delete() or clear().
  • Not length. map.length is undefined. Mixing the two up is the most common mistake when switching between arrays and maps.
  • Plain objects have no size. Count with Object.keys(obj).length, which builds an array first. With a Map the count is stored, so it costs nothing.
  • Emptiness check. map.size === 0 tells you the map is empty. A map object itself is always truthy, even when it is empty.
  • Setting an existing key does not change size. Only new keys increase it.
  • During iteration the value changes as entries are added or removed, so cache it in a variable if you need the original count.
  • Inherited by subclasses. A class that extends Map has the same size getter.

Browser support

Map.prototype.size works in every current browser and in Node.js.