TIL writing cleaner If statements
POSTED ON:
TAGS: javascript cleancode ifstatements
I probably write about this a lot.
This is from Clean Up Your Code by Removing ‘if-else’ Statements, and this is the best version I ever saw of this.
Using If statements #
function action(ranking){
if(ranking == 'A'){
travel()
}
else if (ranking == 'B'){
shopping()
}
else if (ranking == 'C'){
watchTV()
}
else if (ranking == 'D') {
review()
}
}
Using Switch #
function action(ranking){
switch(ranking){
case 'A':
travel()
break
case 'B':
shopping()
break
case 'C':
watchTV()
break
case 'D':
review()
break
}
}
Using Key values #
let strategies = {
'A': travel,
'B': shopping,
'C': watchTV,
'D': review
}
function action(ranking){
let strategy = strategies[ranking]
strategy()
}
Related TILs
Tagged: javascript