Curriculum

Curriculum

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.

Selected choicePick a choice below
Result—
Python
def lookup_room(rooms: dict[str, int], room_id: str) -> int | str:
    return rooms[room_id] if room_id in rooms else "UNKNOWN_ROOM"
JavaScript
export function lookupRoom(rooms, roomId) {
  return Object.hasOwn(rooms, roomId) ? rooms[roomId] : "UNKNOWN_ROOM";
}
Go
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.

Reveal the explanation
  1. Python: room_id in rooms

    Avoids KeyError on "Room-Z" and preserves 0 for "Room-B".

  2. JavaScript: Object.hasOwn(rooms, roomId) / map.has(roomId)

    Avoids treating valid 0 as falsy like "rooms[id] || UNKNOWN".

  3. 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

In Go, why must you use "seats, ok := rooms[roomID]" instead of "seats := rooms[roomID]"?
Show the answer and reasoning

Correct answer Because a missing key returns 0, so ok is needed to tell missing apart from a full room

The boolean ok is true when the key exists (even with value 0) and false when absent.