Optimize complex else if statements in JavaScript

--

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

For e.g., I have a function that returns the discount price based on the coupon code provided by the user. Here have to verify each and 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 each and 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.

Hope this approach will be helpful. Cheers!

--

--