Check Missing Map Keys in Python, JS, and Go
Scenario
Look up "Room-B" (value 0) vs "Room-Z" (missing) across Python, JavaScript, and Go.
def lookup_room(rooms: dict[str, int], room_id: str) -> int | str:
return rooms[room_id] if room_id in rooms else "UNKNOWN_ROOM"export function lookupRoom(rooms, roomId) {
return Object.hasOwn(rooms, roomId) ? rooms[roomId] : "UNKNOWN_ROOM";
}func lookupRoom(rooms map[string]int, roomID string) (int, bool) {
seats, ok := rooms[roomID]
return seats, ok
}Try it yourself
Compare each language’s safe presence check against unsafe direct indexing.
| Case | Result |
|---|---|
| Python: room_id in rooms | Select a choice above to see what happens. |
| JavaScript: Object.hasOwn(rooms, roomId) / map.has(roomId) | Select a choice above to see what happens. |
| Go: seats, ok := rooms[roomID] | Select a choice above to see what happens. |
Reveal the explanation
- Python: room_id in rooms
Avoids KeyError on "Room-Z" and preserves 0 for "Room-B".
- JavaScript: Object.hasOwn(rooms, roomId) / map.has(roomId)
Avoids treating valid 0 as falsy like "rooms[id] || UNKNOWN".
- Go: seats, ok := rooms[roomID]
Crucial in Go! Without ok, missing keys silently return zero-value 0.
Go maps return 0 by default when a key is absent, making the comma-ok idiom (seats, ok := rooms[id]) essential for accurate lookup contracts.
Review first
Download shared test cases
Your turn
Explain why "rooms[id] || 'UNKNOWN_ROOM'" in JavaScript fails for { "Room-B": 0 }.
Common mistake Using || fallback on numeric map values where 0 is a real valid value.
Check your work
0 is falsy in JS, so rooms["Room-B"] || "UNKNOWN_ROOM" wrongly returns "UNKNOWN_ROOM" instead of 0.
Quick check
This browser could not save your progress. Changes last until you leave the page.