
🧠 Replacing Conditionals with Object Literals
In JavaScript, developers often use switch
or if-else
statements to handle multiple conditional branches. However, as the number of cases grows, these structures can become harder to manage and less performant.
A cleaner and more efficient alternative is the Object Literal Lookup, also known as the Object Map Pattern.
⚠️ The Problem with Switch
Take this example:
function handleAction(action) {
switch (action) {
case 'create':
console.log('Creating...');
break;
case 'update':
console.log('Updating...');
break;
case 'delete':
console.log('Deleting...');
break;
default:
console.log('Unknown action');
}
}
As more cases are added, the code becomes longer and more repetitive. Plus, switch statements evaluate each case sequentially until a match is found.
💡 The Solution: Object Literal Lookup
const actions = {
create: () => console.log('Creating...'),
update: () => console.log('Updating...'),
delete: () => console.log('Deleting...'),
default: () => console.log('Unknown action')
};
function handleAction(action) {
(actions[action] || actions.default)();
}
✅ Benefits
-
Constant-time access (O(1)) via key lookup
-
Cleaner and more maintainable code
-
Easily extendable (just add new keys)
🧰 When to Use It
This pattern is especially useful when:
-
Each case represents a distinct and independent behavior
-
You want to avoid long
switch
orif-else
blocks -
You prefer a more declarative or functional style