Checking if a Key Exists
What you'll learn: How to safely check whether a key exists in a Map before trying to retrieve its value.
Why Check First?
When you use get() on a Map, it returns undefined if the key doesn't exist. But what if undefined is actually a valid value you stored? This creates ambiguity—you can't tell the difference between "key doesn't exist" and "key exists with value undefined".
Think of a Map like a filing cabinet. Before you reach into a drawer expecting a document, you might want to check if that drawer even exists—especially if "empty folder" is also a valid thing you might file.
Using has() to Test for Presence
The has() method returns true if the key exists in the Map, and false otherwise:
const userRoles = new Map();
userRoles.set('alice', 'admin');
userRoles.set('bob', 'editor');
userRoles.set('charlie', undefined);
console.log(userRoles.has('alice')); // true
console.log(userRoles.has('charlie')); // true (key exists!)
console.log(userRoles.has('diana')); // false
Notice that has('charlie') returns true even though its value is undefined. The key exists in the Map.
Practical Pattern
Use has() before get() when you need to distinguish between missing keys and stored values:
if (userRoles.has('diana')) {
const role = userRoles.get('diana');
console.log(`Diana's role: ${role}`);
} else {
console.log('Diana is not in the system');
}
This prevents confusion and makes your code's intent crystal clear.
Key Takeaway: Use has() to check if a key exists in a Map before accessing it—this is the only reliable way to distinguish between missing keys and keys with undefined values.