TIL Getting rid of if/else and switch statements
POSTED ON:
TAGS: javascript
Getting rid of if/else and switch statements
// LAME
function getColor(fruit) {
if (fruit.toLowerCase() === 'apple') {
return 'red';
} else if (fruit.toLowerCase() === 'banana') {
return 'yellow';
} if (fruit.toLowerCase() === 'orange') {
return 'orange';
} if (fruit.toLowerCase() === 'blueberry') {
return 'blue';
} if (fruit.toLowerCase() === 'lime') {
return 'green';
}
return 'unknown';
}
// MEH
function getColor(fruit) {
switch(fruit.toLowerCase()) {
case 'apple':
return 'red';
case 'banana':
return 'yellow';
case 'orange':
return 'orange';
case 'blueberry':
return 'blue';
case 'lime':
return 'green';
default:
return 'unknown';
}
}
// VERY NICE
function getColor(fruit) {
const fruits = {
'apple': 'red',
'banana': 'yellow',
'orange': 'orange',
'blueberry': 'blue',
'lime': 'green',
};
return fruits[fruit.toLowerCase()] || 'unknown';
}
via https://blog.logrocket.com/refactoring-cascading-conditionals-favor-readability/
Related TILs
Tagged: javascript