Swapping out switch statements for object literals
23. Januar 2023
switch statements in JavaScript look clunky to me. Aesthetically, I’ve never much enjoyed them. But, the alternative—a long chain of if/else hell—isn’t the one either. So, what do you do?
Well, as we’re often reminded, everything in JavaScript—and they mean everything—is an object. So, why can’t a switch statement be an object too?
Whaaaaaat, you say. I know, I know, we’re in a whole world of weird. But honestly, here’s how it works:
Say you’ve got two options. Perhaps you’re trying to choose between joining Twitter or joining Mastodon. With a switch statement, you might write something like:
const myChoice = 'mastodon';
const outcome;
switch (myChoice) {
case 'twitter':
outcome = 'Abort! Abort! Abort!';
break;
case 'mastodon':
outcome = 'Wahoo! No billionaires.';
break;
default:
outcome = 'Elon: pay your bills.';
}
console.log(outcome); // Wahoo! No billionaires. I mean, look at that. I think it’s the multiple indentations, the use of break that doesn’t feel all that native to the language, and well, the fact that I can never remember where the curlies go.
But don’t despair: here’s how we can use an object literal to make all this madness move over:
const myChoice = 'mastodon';
const hell = () => console.log('Abort! Abort! Abort!');
const heaven = () => console.log('Wahoo! No billionaires.');
const selectPlatform = {
twitter: hell,
mastodon: heaven,
default: heaven,
};
(selectPlatform[myChoice] || selectPlatform['default'])(); // Wahoo! No billionaires.
Bada bing, bada boom. Less code, much more in-keeping with the language, and eminently more readable. Oh, and in case that wasn’t enough, there’s also a performance gain over the traditional switch statement.
Time to get your switch on.