I have multiple if statements in a function like this :
const handleCat = () => {
if (mainCat === 'car') {
return carCat;
}
if (mainCat === 'mobile') {
return mobileCat;
}
if (mainCat === 'estate') {
return estateCat;
}
if (mainCat === 'other') {
return otherCat;
}
};
All the cat's are arrays with objects . I was wondering how can I refactor this code into much more cleaner and easier to read code ? How many ways are there to refactor multiple if statements in javascript ?
One way which I would recommend will be to use an object type.
const genericCat = {
car : carCat,
mobile : mobileCat,
estate:estateCat,
other : otherCat
}
handleCat = (mainCat)=>{
return(generiCat[mainCat])
}
this approch also saves you from updating your code from more then one place if types of cat are increased.This is like using Enums in Java but with objects.
Using a switch
statement:
const handleCat = () => {
switch (mainCat) {
case 'car':
return carCat;
case 'mobile':
return mobileCat;
case 'estate':
return estateCat;
case 'other':
return otherCat;
default:
break;
}
};
A switch statement is an option
const handleCat = (mainCat) => { switch(mainCat) { case "car": return "carCat"; case "mobile": return "mobileCat"; case "estate": return "estateCat"; case "other": return "otherCat"; default: return "fallbackCat"; } }; const first = handleCat("car"); const second = handleCat(); console.log(first); console.log(second);
You could also save the options in an object and return them based on their key.
const handleCat = (mainCat) => { const fallback = "fallbackCat"; const catMap = { car: "carCat", mobile: "mobileCat", estate: "estateCat", other: "otherCat", }; return catMap[mainCat] || fallback; }; const first = handleCat("car"); const second = handleCat(); console.log(first); console.log(second);
You can use a switch statement:
var mainCat = 'car';
const handleCat = () => {
switch(mainCat) {
case 'car':
return carCat;
break;
case 'mobile:
return mobileCat;
break;
case 'estate'
return estateCat;
break;
default:
return otherCat;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.