Map Size Property
You'll learn how to instantly check how many key-value pairs are stored in a Map.
What It Does
Every Map has a built-in size property that tells you exactly how many entries it contains. Unlike arrays where you use length, Maps use size to count their key-value pairs.
Think of it like a restaurant keeping track of how many tables are currently occupied. The size property gives you that count at any moment, automatically updating as guests arrive (entries added) or leave (entries removed).
How to Use It
The size property is read-only—you simply access it:
const menu = new Map();
console.log(menu.size); // 0 (empty Map)
menu.set('burger', 8.99);
menu.set('fries', 3.49);
menu.set('shake', 4.99);
console.log(menu.size); // 3
menu.delete('fries');
console.log(menu.size); // 2
menu.clear();
console.log(menu.size); // 0
Why It Matters
The size property is incredibly useful for:
- Validation: Check if a Map is empty before iterating
- Conditionals: Make decisions based on how many entries exist
- Debugging: Quickly verify how many items you're working with
const users = new Map();
users.set('alice', { age: 30 });
if (users.size > 0) {
console.log(`We have ${users.size} user(s)`);
}
Notice it's a property, not a method—no parentheses needed like size().
Key Takeaway: Use the size property to get the current number of entries in a Map; it updates automatically and reflects the Map's state in real-time.