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.
const m = new Map([["a", 1], ["b", 2]]); m.size; // 2
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
TypeErrorin strict mode (modules and classes are strict). To shrink a map, calldelete()orclear(). - Not
length.map.lengthisundefined. 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 aMapthe count is stored, so it costs nothing. - Emptiness check.
map.size === 0tells 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
Maphas the samesizegetter.
Browser support
Map.prototype.size works in every current browser and in Node.js.
Related
- Map
- Map.prototype.has() and delete()
- Set
- Lesson: Maps
- Lesson: Sets