Getting Values by Key
You'll learn how to retrieve values from a Map using the get() method and what happens when a key doesn't exist.
How get() Works
Once you've stored key-value pairs in a Map using set(), you retrieve values with the get() method. Simply pass the key you want to look up, and the Map returns its associated value:
const userRoles = new Map();
userRoles.set('alice', 'admin');
userRoles.set('bob', 'editor');
console.log(userRoles.get('alice')); // 'admin'
console.log(userRoles.get('bob')); // 'editor'
Missing Keys Return undefined
Here's the important part: if you ask for a key that doesn't exist in the Map, get() returns undefined (it doesn't throw an error):
console.log(userRoles.get('charlie')); // undefined
This is different from accessing a non-existent property on an object, which also returns undefined but can be ambiguous. With Maps, you'll later have ways to distinguish between "key doesn't exist" and "key exists with value undefined."
Think of It Like a Lookup Table
Imagine a Map as a filing cabinet where each drawer has a unique label (the key). When you use get(), you're opening the drawer with that label and taking out whatever's inside. If there's no drawer with that label, you get nothing (undefined) instead of an error.
Key Takeaway: Use map.get(key) to retrieve values; missing keys safely return undefined rather than causing errors.