Optimize complex else if statements in JavaScript

2 min readFeb 27, 2023

Sometimes we have to write complex else-if statements to verify multiple conditions.

E.g., I have a function that returns the discount price based on the coupon code provided by the user. Here, I have to verify every statement which takes a long time.

Method that returns Discount Price

Approach 1 :

The first way to optimize this issue is by using a switch case. In which we don’t need to verify every statement. Instead based on the coupon code we can directly jump to the respective condition.

Approach 2 :

This is the best way to verify multiple conditions. Create an object with all the coupon codes and return the discount price based on the condition. If we provide an invalid coupon code, it will return zero.


While working on complex if-else statements return early when invalid conditions occur.

For example, here price of an item will be updated only when the provided price is greater than 0 and it is updated by an authorized user.

This can be further reduced by inverting the conditions as shown below.

Hope this helps😀🫠