Original post at toncho.dev
We are going to see how object lookups can sometimes be used as a more maintainable alternative to if and switch statements.
Swtich
The switch
statement evaluates an expression, matching the value to a case
clause, and then executes statements associated. What switch does is take input and provide an output based on the case
clause.
const type = 'apple';
let fruit;
switch(type) {
case 'apple':
fruit = 'Apple';
break;
case 'pear':
fruit = 'Pear';
break;
default:
fruit = 'Unknown fruit!';
break;
}
console.log(fruit);
// expected output: "Apple"
There are many problems with switch
statement, it has non standard way to handle code blocks, the rest of JavaScript uses curly braces but switch does not. We are forced to add break
statements within each case, which can lead to difficult debugging, make mistakes when writing each case
clause for often forget to add this break
statement, also the number of case
clause increases, the performance of the object gets better than the average cost of the switch where the order of the cases matter. The object approach is a hash table lookup, and the switch has to evaluate each case until it hits a match and a break.
If and Else
The if
and else
statements are similar to switch
, but it evaluate a single value, if the specified condition is truthy the if
statement executes otherwiese if the condition is falsy the else
statements executes, when they are a lot of else if
statements, something is really wrong and generally you should use something like switch
as itβs more suited for the purpose and intention.
const getFruit = (type) => {
if (type === 'apple') {
type = 'Apple';
} else if (type === 'pear') {
type = 'Pear';
} else {
type = 'Unknown fruit!';
}
return type;
}
const type = 'apple';
console.log(getFruit(type));
// expected output: "Apple"
Object Lookups
We use Objects all the time, either as constructors or literals. We are going to get values from the Object properties.
const getFruit = (type) => {
return {
'apple': 'Apple',
'pear': 'Pear',
}[type];
}
const type = 'apple';
console.log(getFruit(type));
// expected output: "Apple"
This example is mapping one value to another one. with the object lookup we provide a cleaner way to write the code, we don't have to worry about case
clause or break
statement and it's easier to read and quickly understand what's going on.
Top comments (0)