Writing quality conditional logic is a huge part of programming. Realistically, you could even say it’s the main aspect of the job. In the job, there are two core ways to do this: if....else
and switch...case...case...default
. If/else and switch statements are the core of conditionals in JS. So naturally, making them as optimized as possible is important. Today, we’ll be looking at optimizing our switch statements.
Standard switch statements determine which logic to run based on a variable that’s been passed in and seeing if it matches any of our designated cases
. For our test code, we’ll call this variable value
. In shorthand, however, we can streamline this a bit with a simple object.
Let’s look at the code!
// Traditional Switch Statement
switch (value) {
case 1:
console.log('this is 1');
break;
case 2:
console.log('this is 2');
break;
case 3:
console.log('this is 3');
break;
case 4:
console.log('this is 4');
break;
default:
console.log('this does not match cases');
break;
}
// Optomized ShortHand
const switchStatement = {
1: () => console.log('this is 1'),
2: () => console.log('this is 2'),
3: () => console.log('this is 3'),
4: () => console.log('this is 4'),
default: () => console.log('this does not match cases')
};
const statement = switchStatement[value] || switchStatement.default
statement();
Simple and easy, with fewer lines written as well. Give it a shot in your next project and see!