Conditional statements and objects - are we talking about the same thing here? Do they have anything in common? Not quite similar, but you could simplify your conditional statements using objects.
Consider the below tax rate calculation logic -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
const incomeLevel = "high";
let taxRate;
if (incomeLevel == "very low") {
taxRate = income * 0.1;
} else if (incomeLevel == "low") {
tax = income * 0.3;
} else if (incomeLevel == "medium") {
taxRate = income * 0.4;
} else taxRate = 0;
console.log("tax rate:", taxRate);
// 0
|
The multiple if
s can be avoided by using a simple object -
1
2
3
4
5
6
7
8
|
const incomeLevel = "very low";
const taxRateRef = { "very low": 0.1, low: 0.3, medium: 0.4, high: 0 };
const taxRate = taxRateRef[incomeLevel];
console.log("tax:", taxRate);
// 0.1
|
Both objects and arrays alike find a lot of use in real-world scenarios to avoid complex loops. They also keep code simple, readable and maintainable.