Map.prototype.size
Counting an object means building an array of its keys first. A Map just knows, which is one of the quieter reasons to prefer it for collections that change.
Demo
The count is of ENTRIES, and the second case shows why that matters when building from pairs: a repeated key does not add a second entry, it overwrites the first, so three input pairs can yield fewer entries than you passed. The last case confirms keys of different types coexist happily — a string, a number and a boolean are three distinct keys. Note there are no parentheses: size is a getter.
Common patterns
if (map.size === 0) return;
const unique = new Map(pairs).size;
Object.keys(obj).length;
Examples
Pitfalls
const m = new Map(); m.size()
new Map().size
const m = new Map([["a", 1]]); m.size = 0; m.size
m.clear(); m.size
new Map([["a", 1], ["a", 2]]).size
const pairs = [["a", 1], ["a", 2]]; pairs.length !== new Map(pairs).size
({a: 1}).length
Object.keys({a: 1}).length
When to use
- Counting entries, or testing for emptiness
- Anywhere Object.keys(obj).length appears in a loop
- Detecting duplicate keys when building from pairs
- Counting values that satisfy a predicate → filter a spread
- You want to truncate → clear, or rebuild
- The collection is a WeakMap → it has no size, by design
Notes
FAQ
length belongs to ordered, indexable things — arrays and strings. Map and Set are unordered collections in the indexing sense, so the specification uses size, as it does for the other ES2015 collections. It also keeps the two from being confused.