Every else-if chain starts small. Two cases, maybe three. Then a fourth gets added during a sprint. Then a fifth. Before long, you're staring at a wall of conditional logic that nobody wants to touch, and adding a new case means scrolling through thirty lines to find the right spot.
There's a cleaner way. And you already know the tool — you just haven't thought of it this way.
The Problem
Look at this and tell me it scales:
let fruit = 'apple';
if (fruit === 'apple') {
console.log('Apple is great for making pies.');
} else if (fruit === 'banana') {
console.log('Bananas are great for smoothies.');
} else if (fruit === 'cherry') {
console.log('Cherries make delicious jam.');
} else {
console.log('This is a fruit I don\'t know much about.');
}
Four cases and it's already tedious. Ten cases and it's unreadable. Twenty and it's unmaintainable. Every addition increases the risk of accidentally breaking an existing branch.
Objects Are Already Maps
JavaScript objects are key-value stores. You've been using them that way your whole career. The insight is using them to replace branching logic:
let fruit = 'apple';
let fruitMap = {
apple: 'Apple is great for making pies.',
banana: 'Bananas are great for smoothies.',
cherry: 'Cherries make delicious jam.',
default: 'This is a fruit I don\'t know much about.'
};
console.log(fruitMap[fruit] || fruitMap.default);
Adding a new fruit is one line. No brackets, no control flow, no risk of breaking what's already there. The lookup is O(1) instead of O(n). The code reads like data, not logic.
When You Need More Than Strings
Sometimes each case needs to do something, not just return a value. Store functions:
let fruit = 'apple';
let fruitActions = {
apple: () => console.log('Making an apple pie...'),
banana: () => console.log('Making a banana smoothie...'),
cherry: () => console.log('Making cherry jam...'),
default: () => console.log('I don\'t know what to make with this fruit.')
};
let action = fruitActions[fruit] || fruitActions.default;
action();
Same pattern. Same benefits. Now your conditional logic is a data structure that you can iterate, test, serialize, or extend without touching the dispatch code.
The next time you catch yourself typing else if, stop. Reach for an object instead. Your future self — and everyone who reads your code — will thank you.
