When to Prefer Object Lookups
You'll learn when using an object (or Map) to retrieve values is clearer and simpler than a long switch statement.
The Core Idea
Sometimes you're writing a switch statement where every case does the exact same thing: it matches a value and returns or assigns a corresponding result. When this pattern emerges—no complex logic, just value-to-value mapping—an object lookup is often more readable and concise.
Think of it like a dictionary. If you're translating words from English to Spanish, you don't write a giant flowchart with arrows for every word. You just look up the word in a dictionary. Objects work the same way for simple mappings.
When Objects Shine
Use an object lookup when:
- Every case returns or assigns a single value
- No fall-through behavior is needed
- The logic is purely "input A → output B"
// Switch approach (more verbose)
let color;
switch (status) {
case 'pending':
color = 'yellow';
break;
case 'approved':
color = 'green';
break;
case 'rejected':
color = 'red';
break;
default:
color = 'gray';
}
// Object lookup (cleaner for simple mappings)
const statusColors = {
pending: 'yellow',
approved: 'green',
rejected: 'red'
};
const color = statusColors[status] || 'gray';
The object version is shorter, easier to scan, and separates the data (the mapping) from the logic.
When to Stick with Switch
If your cases need to execute multiple statements, perform calculations, or share code via fall-through, switch remains the better choice.
Key Takeaway: Prefer object lookups over switch when you're doing simple value-to-value mapping with no complex logic—it's clearer, more concise, and easier to maintain.