This page looks best with JavaScript enabled

Simplify Conditionals Using Objects in Javascript

 ·   ·  ☕ 1 min read

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 ifs 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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things